“str”对象在实现 SQL Alchemy 时在 fastapi 中没有属性“c”错误

问题描述 投票:0回答:1

我正在从 freecodingcamp 学习 FastAPI。我遇到了一个问题:

这是我的文件结构:

App
|_ database.py
|_ main.py
|_ models.py
|_ __init__.py

这是我的

main.py
文件

from fastapi import Body, Depends, FastAPI,Response,status,HTTPException
from fastapi.params import Body
from pydantic import BaseModel
from random import randrange
import psycopg2
from psycopg2.extras import RealDictCursor
import time
from sqlalchemy.orm import Session
from database import Base
import models
from database import engine,SessionLocal
# from requests import Response
app = FastAPI()

models.Base.metadata.create_all(bind=engine)


def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

class postparam(BaseModel):
    title: str
    content:str
    Published: bool =True
    
while True:
    try:
        conn = psycopg2.connect(host= 'localhost',database='FastApi',user='postgres',password='2580',cursor_factory=RealDictCursor)
        cursor = conn.cursor()
        print('Database connection Established!!')
        break
    except Exception as error:
        print("connection to database failed !!")
        print('Error: ',error)
        time.sleep(2)


@app.get("/sql")
async def root(db:Session =Depends(get_db)):
    return {"message":"this is a sample fastapi"}

这就是我的

database.py
文件的样子:

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

SQLALCHEMY_DATABASE_URL = "postgresql://postgres:2580@localhost/Fastpi"  #use os.join from local variable
# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db"

engine = create_engine(
    SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

这是我的

models.py
文件:

# from tokenize import String
from sqlalchemy import Column,Integer,String,Boolean
from sqlalchemy.sql.expression import null
from database import Base


class Post(Base):
    __table__ = 'posts'
    id = Column(Integer,primary_key= True,nullable=False)
    name = Column(String,nullable =False)
    content = Column(String,nullable = False)
    published = Column(Boolean,default= False)

This is my output in Powershell

python postgresql sqlalchemy orm fastapi
1个回答
0
投票

在您的

Post
模型中,您要覆盖
__table__
- 这是 SQLAlchemy 使用的内部值。

您正在寻找

__tablename__

class Post(Base):
    __tablename__ = 'posts'

    id = Column(Integer,primary_key= True,nullable=False)
    name = Column(String,nullable =False)
    content = Column(String,nullable = False)
    published = Column(Boolean,default= False)
© www.soinside.com 2019 - 2024. All rights reserved.