重复检查FastAPI中ID路径参数
我有以下路线规格:
GET /councils/{id}
PUT /councils/{id}
DELETE /councils/{id}
在所有三个路线中,我必须在数据库中检查是否存在id
的理事会,例如:
council = crud.council.get_by_id(db=db, id=id)
if not council:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Council not found'
)
这增加了代码中的许多样板。有什么方法可以减少这一点吗?我已经想到了创建依赖性,但是随后我必须为数据库中的不同模型编写不同的依赖性功能。有什么标准做法吗? 谢谢。
I have the following route specs:
GET /councils/{id}
PUT /councils/{id}
DELETE /councils/{id}
In all three routes, I have to check in the database whether the council with the id
exists, like this:
council = crud.council.get_by_id(db=db, id=id)
if not council:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Council not found'
)
Which adds to a lot of boilerplate in the code. Is there any way of reducing this? I have thought of creating a dependency but then I have to write different dependency function for different models in my database. Is there any standard practice for this?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用依赖性是要走的方法 - 它允许您提取围绕“从URL获得有效理事会”的逻辑;如果要映射
/</>/< id>
始终从特定模型中检索某些内容,则可以进一步概括它;但是 - 您可能需要根据一组可能的值对此进行验证,以避免人们试图在模型类中加载随机的Python标识符。您可以概括依赖关系定义以使其可重复使用(我现在没有任何可用的测试,但是这个想法应该起作用):
Using a dependency is the way to go - it allows you to extract the logic around "get a valid council from the URL"; you can generalize it further if you want to map
/<model>/<id>
to always retrieving something from a specific model; however - you might want to validate this against a set of possible values to avoid people trying to make you load random Python identifiers in your models class.You can generalize the dependency definition to make it reusable (I don't have anything available to test this right now, but the idea should work):
这是一种有效的解决方案。 FastApi支持类作为依赖项。因此,我可以拥有这样的类:
考虑
crud
模块将为所有ORM模型导入CRUD类。我的示例紧随 fastapapi cookiecutter项目他遵循的模式。现在,为了使用它,例如在
consems_route.py
中,我可以做以下操作:Here is one solution that works. FastAPI supports classes as dependencies. Therefore I can have a class like this:
Considering
crud
module imports the crud classes for all the ORM models. My example is closely following the fastAPI cookiecutter project by Tiangolo, and the crud design pattern he followed.Now in order to use it, for example in
councils_route.py
, I can do the following: