Dat*_*ery 32 python get pydantic fastapi
这是我的数据库架构。
\n\n我这样定义我的架构:
\n从 pydantic 导入 BaseModel
\nclass Userattribute(BaseModel):\n name: str\n value: str\n user_id: str\n id: str\nRun Code Online (Sandbox Code Playgroud)\n这是我的模型:
\nclass 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)\nRun Code Online (Sandbox Code Playgroud)\n在 crud.py 中我定义了一个get_attributes方法。
def get_attributes(db: Session, skip: int = 0, limit: int = 100):\n return db.query(models.Userattribute).offset(skip).limit(limit).all()\nRun Code Online (Sandbox Code Playgroud)\n这是我的GET终点:
@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\nRun Code Online (Sandbox Code Playgroud)\n与数据库的连接似乎可以工作,但问题在于数据类型:
\npydantic.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)\nRun Code Online (Sandbox Code Playgroud)\n为什么 FASTApi 需要字典?我不\xc2\xb4t 真正理解它,因为我什至无法打印响应。我怎样才能解决这个问题?
\nMat*_*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。
| 归档时间: |
|
| 查看次数: |
53917 次 |
| 最近记录: |