由网友(餅干ノ亅丶ωц老奶奶`※)分享简介:所以我需要在类中有一些路由,但是路由方法需要有selfattr(以访问类的属性)。但是,FastAPI随后假定self是它自己的必需参数,并将其作为查询参数放入这是我得到的:app = FastAPI()class Foo:def __init__(y: int):self.x = y@app.get("/so...![如图网络组建 路由器映射不起来 两个路由不能通](https://p.xsw88.cn/allimgs/daicuo/20230903/3147.png)
所以我需要在类中有一些路由,但是路由方法需要有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
是字符串,因此毫无用处。
![如图网络组建 路由器映射不起来 两个路由不能通](https://p.xsw88.cn/allimgs/daicuo/20230903/3147.png)
我需要某种方法,使我仍然可以访问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)
相关推荐
最新文章