在 FastApi 中切换到路由器并不顺利。 response_model List[] pydantic 字段类型错误
Switching To Routers in FastApi did not go well. response_model List[] pydantic field type error
我有一个使用 FastApi 的 Python 3.8 应用程序。 main.py
中的路由太多了,所以我接受了从 FastApi application
对象切换到 router
并将每个 db table 的路由放在它自己的文件中。到目前为止,由于 response_model
装饰器的解释,它还没有奏效。
开关导致我修改后的代码在使用 response_model 装饰器 Post
时出现问题。最大的区别是我在 main.
中使用 router
装饰器而不是 application
装饰器
我遇到的具体错误是:
File "/Users/markwardell/PycharmProjects/pythonProject/venv/lib/python3.8/site-packages/fastapi/utils.py", line 67, in create_response_field
raise fastapi.exceptions.FastAPIError(
fastapi.exceptions.FastAPIError: Invalid args for response field! Hint: check that typing.List[models.Post] is a valid pydantic field type
导致此错误的代码在 post.py
中,我从 main.py
中分离出来
post.py
从 fastapi 导入 HTTPException,APIRouter
来自 sqlalchemy.orm 导入会话
从键入导入列表
来自 fastapi.params 导入取决于
import models
from database import get_db
router: APIRouter = APIRouter()
@router.get("/postss", response_model=List[models.Post])
def get_post(db: Session = Depends(get_db)):
# cursor.execute("""SELECT * FROM posts""")
# posts = cursor.fetchall()
# print(posts)
try:
posts = db.query(models.Post).all()
except Exception as ex:
msg = f"Unexpected {ex=}, {type(ex)=}"
raise HTTPException(status_code=500, detail=msg)
return posts
有效的原始代码:
main.py
从 fastapi 导入 FastAPI、响应、HTTPException
来自 fastapi.params 导入 视情况而定
来自 starlette 导入状态
导入用户
导入 post
import models
import schemas
from database import engine, get_db
from sqlalchemy.orm import Session
models.Base.metadata.create_all(bind=engine)
app = FastAPI()
app.include_router(user.router)
app.include_router(post.router)
if __name__ == "__main__":
uvicorn.run(app, host="127.0.0.1", port=8000)
@app.get("/")
async def root():
return {"message": "Welcome To My Api!"}
@app.get("/posts", response_model=List[schemas.Post])
def get_posts(db: Session = Depends(get_db)):
# cursor.execute("""SELECT * FROM posts""")
# posts = cursor.fetchall()
# print(posts)
try:
posts = db.query(models.Post).all()
except Exception as ex:
msg = f"Unexpected {ex=}, {type(ex)=}"
raise HTTPException(status_code=500, detail=msg)
return posts
这里是 response_model(s)
的定义
schema.py
from datetime import datetime
from pydantic import BaseModel, EmailStr
class PostBase(BaseModel):
title: str
content: str
published: bool = True
class PostCreate(BaseModel):
pass
class Post(PostBase):
id: int
created_at: datetime
class Config:
orm_mode = True
arbitrary_types_allowed = True
class UserCreate(BaseModel):
email: EmailStr
password: str
class UserOut(BaseModel):
id: int
email: EmailStr
created_at: datetime
class Config:
orm_mode = True
您的 response_model
定义中的 class 类型错误;参考应指向您的架构(继承自 pydantic 的 BaseModel
)-您的 response_model
指向您的 SQLAlchemy 模型(即模块名称中的 schema
与 model
)。
我有一个使用 FastApi 的 Python 3.8 应用程序。 main.py
中的路由太多了,所以我接受了从 FastApi application
对象切换到 router
并将每个 db table 的路由放在它自己的文件中。到目前为止,由于 response_model
装饰器的解释,它还没有奏效。
开关导致我修改后的代码在使用 response_model 装饰器 Post
时出现问题。最大的区别是我在 main.
router
装饰器而不是 application
装饰器
我遇到的具体错误是:
File "/Users/markwardell/PycharmProjects/pythonProject/venv/lib/python3.8/site-packages/fastapi/utils.py", line 67, in create_response_field
raise fastapi.exceptions.FastAPIError(
fastapi.exceptions.FastAPIError: Invalid args for response field! Hint: check that typing.List[models.Post] is a valid pydantic field type
导致此错误的代码在 post.py
中,我从 main.py
post.py
从 fastapi 导入 HTTPException,APIRouter 来自 sqlalchemy.orm 导入会话 从键入导入列表 来自 fastapi.params 导入取决于
import models
from database import get_db
router: APIRouter = APIRouter()
@router.get("/postss", response_model=List[models.Post])
def get_post(db: Session = Depends(get_db)):
# cursor.execute("""SELECT * FROM posts""")
# posts = cursor.fetchall()
# print(posts)
try:
posts = db.query(models.Post).all()
except Exception as ex:
msg = f"Unexpected {ex=}, {type(ex)=}"
raise HTTPException(status_code=500, detail=msg)
return posts
有效的原始代码:
main.py
从 fastapi 导入 FastAPI、响应、HTTPException 来自 fastapi.params 导入 视情况而定 来自 starlette 导入状态 导入用户 导入 post
import models
import schemas
from database import engine, get_db
from sqlalchemy.orm import Session
models.Base.metadata.create_all(bind=engine)
app = FastAPI()
app.include_router(user.router)
app.include_router(post.router)
if __name__ == "__main__":
uvicorn.run(app, host="127.0.0.1", port=8000)
@app.get("/")
async def root():
return {"message": "Welcome To My Api!"}
@app.get("/posts", response_model=List[schemas.Post])
def get_posts(db: Session = Depends(get_db)):
# cursor.execute("""SELECT * FROM posts""")
# posts = cursor.fetchall()
# print(posts)
try:
posts = db.query(models.Post).all()
except Exception as ex:
msg = f"Unexpected {ex=}, {type(ex)=}"
raise HTTPException(status_code=500, detail=msg)
return posts
这里是 response_model(s)
的定义schema.py
from datetime import datetime
from pydantic import BaseModel, EmailStr
class PostBase(BaseModel):
title: str
content: str
published: bool = True
class PostCreate(BaseModel):
pass
class Post(PostBase):
id: int
created_at: datetime
class Config:
orm_mode = True
arbitrary_types_allowed = True
class UserCreate(BaseModel):
email: EmailStr
password: str
class UserOut(BaseModel):
id: int
email: EmailStr
created_at: datetime
class Config:
orm_mode = True
您的 response_model
定义中的 class 类型错误;参考应指向您的架构(继承自 pydantic 的 BaseModel
)-您的 response_model
指向您的 SQLAlchemy 模型(即模块名称中的 schema
与 model
)。