如何在类内使用FastAPI创建路由

编程入门 行业动态 更新时间:2024-10-15 04:19:19
本文介绍了如何在类内使用FastAPI创建路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

所以我需要在类中有一些路由,但是路由方法需要有selfattr(以访问类的属性)。 但是,FastAPI随后假定self是它自己的必需参数,并将其作为查询参数放入

这是我得到的:

app = FastAPI() class Foo: def __init__(y: int): self.x = y @app.get("/somewhere") def bar(self): return self.x 但是,除非您转到/somewhere?self=something,否则将返回422。这样做问题是self是字符串,因此毫无用处。

我需要某种方法,使我仍然可以访问self,而不将其作为必需的参数。

推荐答案

要创建基于类的视图,您可以使用@cbv修饰器fastapi-utils。使用它的动机:

停止在相关终结点的签名中反复重复相同的依赖项。

您的样本可以重写如下:

from fastapi import Depends, FastAPI from fastapi_utils.cbv import cbv from fastapi_utils.inferring_router import InferringRouter def get_x(): return 10 app = FastAPI() router = InferringRouter() # Step 1: Create a router @cbv(router) # Step 2: Create and decorate a class to hold the endpoints class Foo: # Step 3: Add dependencies as class attributes x: int = Depends(get_x) @router.get("/somewhere") def bar(self) -> int: # Step 4: Use `self.<dependency_name>` to access shared dependencies return self.x app.include_router(router)

更多推荐

如何在类内使用FastAPI创建路由

本文发布于:2023-11-24 12:43:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1625246.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路由   如何在   FastAPI

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!