python - 无法使用 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
解决方案
SQLAlchemy 的update
对象方法需要一个字典。你给它一个 pydantic 基础模型。
Pydantic 的 BaseModel 支持将对象的属性作为字典返回的dict()
方法。您可以将此字典提供给您的方法:update
test.update(request.dict())
另请注意,该request
名称用于 FastAPI 中的其他内容,可能不是路由参数的好名称。该id
名称也是对内置 Python 函数的引用,因此您通常需要命名它test_id
或类似的名称。
推荐阅读
- reactjs - 使用基于 javascript 的路由器在 react-admin 上重新加载页面
- wpf - 列表框中的 VB.NET WPF 选定项 - 不能多次触发选定项
- sql - SQL Server 视图:从审计表中分配历史员工部门
- c++ - C++,可以采用 ifstream 或 istringstream 的函数
- java - 如果在同步块内完成简单的写入,那么在另一个同步块中的读取是一致的吗?
- mql4 - MQL4 StringToDouble 改变变量的值?
- python - 如何在 Django-rest-Framework 中获取相关对象的列表
- javascript - 为什么我的函数对平均工资问题返回不正确的答案
- r - 按时间创建图表
- python-3.x - Python 错误:RuntimeError:无法访问 /dev/mem。尝试以 root 身份运行!(尝试了所有建议)