FastAPI - GET 请求导致类型错误(值不是有效的字典)

Dat*_*ery 32 python get pydantic fastapi

这是我的数据库架构。

\n

在此输入图像描述

\n

我这样定义我的架构:

\n

从 pydantic 导入 BaseModel

\n
class Userattribute(BaseModel):\n    name: str\n    value: str\n    user_id: str\n    id: str\n
Run Code Online (Sandbox Code Playgroud)\n

这是我的模型:

\n
class Userattribute(Base):\n    __tablename__ = "user_attribute"\n\n    name = Column(String)\n    value = Column(String)\n    user_id = Column(String)\n    id = Column(String, primary_key=True, index=True)\n
Run Code Online (Sandbox Code Playgroud)\n

在 crud.py 中我定义了一个get_attributes方法。

\n
def get_attributes(db: Session, skip: int = 0, limit: int = 100):\n    return db.query(models.Userattribute).offset(skip).limit(limit).all()\n
Run Code Online (Sandbox Code Playgroud)\n

这是我的GET终点:

\n
@app.get("/attributes/", response_model=List[schemas.Userattribute])\ndef read_attributes(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):\n    users = crud.get_attributes(db, skip=skip, limit=limit)\n    print(users)\n    return users\n
Run Code Online (Sandbox Code Playgroud)\n

与数据库的连接似乎可以工作,但问题在于数据类型:

\n
pydantic.error_wrappers.ValidationError: 7 validation errors for Userattribute\nresponse -> 0\n  value is not a valid dict (type=type_error.dict)\nresponse -> 1\n  value is not a valid dict (type=type_error.dict)\nresponse -> 2\n  value is not a valid dict (type=type_error.dict)\nresponse -> 3\n  value is not a valid dict (type=type_error.dict)\nresponse -> 4\n  value is not a valid dict (type=type_error.dict)\nresponse -> 5\n  value is not a valid dict (type=type_error.dict)\nresponse -> 6\n  value is not a valid dict (type=type_error.dict)\n
Run Code Online (Sandbox Code Playgroud)\n

为什么 FASTApi 需要字典?我不\xc2\xb4t 真正理解它,因为我什至无法打印响应。我怎样才能解决这个问题?

\n

Mat*_*ndh 77

Pydantic 2 改变了模型的配置方式,因此如果您使用的是最新版本的 Pydantic,请参阅下面名为 Pydantic 2 的部分。

SQLAlchemy 不返回字典,这是 pydantic 默认所期望的。您可以将模型配置为还支持从标准 orm 参数加载(即对象上的属性而不是字典查找):

class Userattribute(BaseModel):
    name: str
    value: str
    user_id: str
    id: str

    class Config:
        orm_mode = True
Run Code Online (Sandbox Code Playgroud)

您还可以在调用之前附加一个调试器return以查看返回的内容。

由于这个答案已经变得有点流行,我还想提一下,您可以orm_mode = True通过继承自以下内容的公共父类来为模式类设置默认值BaseModel

class OurBaseModel(BaseModel):
    class Config:
        orm_mode = True


class Userattribute(OurBaseModel):
    name: str
    value: str
    user_id: str
    id: str
Run Code Online (Sandbox Code Playgroud)

如果您想支持orm_mode大多数类(对于那些不支持的类,请从常规类继承BaseModel),这非常有用。

派丹提克 2

ConfigPydantic 2用一个字段替换了内部类model_config

from pydantic import ConfigDict

class OurBaseModel(BaseModel):
    model_config = ConfigDict(from_attributes=True)
Run Code Online (Sandbox Code Playgroud)

这与旧的工作方式相同orm_mode

  • 谢谢,就我而言,我从另一个开发人员那里得到了代码,他有拼写错误“类配置:” (4认同)
  • 在我的父类中使用“orm_mode”修复了它......谢谢 (2认同)