如何在类内使用FastAPI创建路由 [英] How to create routes with FastAPI within a class
本文介绍了如何在类内使用FastAPI创建路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我需要在类中有一些路由,但是路由方法需要有self
attr(以访问类的属性)。
但是,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创建路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文