推荐答案
在 FastAPI 中,创建依赖项可以通过定义一个函数或类,并使用 Depends 来声明依赖关系。以下是一个简单的示例:
// www.javascriptcn.com code example
from fastapi import Depends, FastAPI
app = FastAPI()
def common_parameters(q: str = None, skip: int = 0, limit: int = 100):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: dict = Depends(common_parameters)):
return commons在这个示例中,common_parameters 是一个依赖项函数,它返回一个包含查询参数的字典。read_items 路由函数通过 Depends 声明了对 common_parameters 的依赖。
本题详细解读
1. 依赖项的基本概念
依赖项是 FastAPI 中用于处理共享逻辑的一种机制。它们可以用于验证请求、数据库连接、权限检查等场景。依赖项可以是函数、类或异步函数。
2. 创建依赖项
依赖项通常是一个函数,它可以接受参数并返回一个值。这个值可以是任何类型的数据,例如字典、对象等。依赖项函数可以像普通函数一样定义:
def common_parameters(q: str = None, skip: int = 0, limit: int = 100):
return {"q": q, "skip": skip, "limit": limit}3. 使用 Depends 声明依赖
在路由函数中,可以通过 Depends 来声明对某个依赖项的依赖。Depends 是一个特殊的类,它接受一个依赖项函数作为参数:
@app.get("/items/")
async def read_items(commons: dict = Depends(common_parameters)):
return commons在这个例子中,read_items 函数依赖于 common_parameters 函数。当请求到达 /items/ 路由时,FastAPI 会自动调用 common_parameters 函数,并将其返回值传递给 read_items 函数。
4. 依赖项的嵌套
依赖项可以嵌套使用,即一个依赖项可以依赖于另一个依赖项。例如:
// www.javascriptcn.com code example
def get_db():
db = "fake_db"
try:
yield db
finally:
print("Closing DB connection")
def get_user(db: str = Depends(get_db)):
return {"user": "John Doe", "db": db}
@app.get("/user/")
async def read_user(user: dict = Depends(get_user)):
return user在这个例子中,get_user 依赖于 get_db,而 read_user 又依赖于 get_user。
5. 异步依赖项
如果依赖项需要执行异步操作,可以将其定义为异步函数:
async def common_async_parameters(q: str = None, skip: int = 0, limit: int = 100):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: dict = Depends(common_async_parameters)):
return commons6. 依赖项的生命周期
依赖项可以有不同的生命周期。默认情况下,依赖项在每次请求时都会被调用。如果依赖项需要在整个应用程序生命周期内共享,可以使用 lru_cache 或 singleton 模式来缓存依赖项的结果。
// www.javascriptcn.com code example
from functools import lru_cache
@lru_cache()
def get_settings():
return {"setting1": "value1", "setting2": "value2"}
@app.get("/settings/")
async def read_settings(settings: dict = Depends(get_settings)):
return settings在这个例子中,get_settings 的结果会被缓存,直到应用程序重启。