【问题标题】:Cannot update with FastAPI无法使用 FastAPI 更新
【发布时间】:2021-05-10 14:20:32
【问题描述】:

当我使用以下代码从 FastAPI 文档运行 put 时,我得到 500 Error: Internal Server Error`` and the terminal shows AttributeError: 'Test' object has no attribute ' items'```` 并且终端显示 AttributeError: 'Test' object has no attribute 'items'

我可以正常创建、获取、删除等,但由于某种原因我不能随便放。

另外,如果我尝试输入一个不存在的 ID,我通常会收到 404 错误。

如果你能告诉我更多关于它的信息,我将不胜感激。

路由器

@router.put('/{id}', status_code=status.HTTP_202_ACCEPTED)
def update(id, request:schemas.Test ,db:Session = Depends(get_db)):
    test= db.query(models.Test).filter(models.Test.id == id)
    if not test.first():
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f'Test with id {id} is not found')
    test.update(request)
    db.commit()
    return 'updated'

型号

from sqlalchemy import Column, Integer, String
from db import Base

class Test(Base):
    __tablename__ = 'tests'
    id = Column('id',Integer, primary_key=True,index=True)
    title = Column('title',String(256))

模式

from pydantic import BaseModel

class Test(BaseModel):
    title:str

【问题讨论】:

    标签: python fastapi


    【解决方案1】:

    SQLAlchemy 的 update 对象方法需要一个字典。你给它一个 pydantic 基础模型。

    Pydantic 的 BaseModel 支持 dict()return the object's properties as a dictionary 的方法。您可以将此字典提供给您的 update 方法:

    test.update(request.dict())
    

    还要注意request 名称用于 FastAPI 中的其他内容,可能不是路由参数的好名称。 id 名称也是对内置 Python 函数的引用,因此您通常希望将其命名为 test_id 或类似名称。

    【讨论】:

      猜你喜欢
      • 2022-07-20
      • 2021-11-15
      • 2023-04-09
      • 2020-08-21
      • 1970-01-01
      • 1970-01-01
      • 2019-10-14
      • 1970-01-01
      • 2022-01-25
      相关资源
      最近更新 更多