首页 > 解决方案 > 无法使用 FastAPI 更新

问题描述

当我使用以下代码从 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

标签: pythonfastapi

解决方案


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

Pydantic 的 BaseModel 支持将对象的属性作为字典返回的dict()方法。您可以将此字典提供给您的方法:update

test.update(request.dict())

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


推荐阅读