关于如何向FastAPI的依赖函数添加参数

本文介绍了FastAPI中如何通过Depends进行依赖注入,包括从路径参数、查询参数以及请求对象中获取数据。示例展示了如何定义依赖函数,并在路由中使用,以及在路由层面设置依赖。此外,还展示了如何将request对象作为参数传递。
摘要由CSDN通过智能技术生成
  1. 通过path 或者query添加参数
from fastapi import Depends, FastAPI

app = FastAPI()

async def my_dependency_function(item_id: int):
    return {"item_id": item_id}


@app.get("/items/{item_id}")
async def read_item(item_id: int, my_dependency: dict = Depends(my_dependency_function):
    return my_dependency
  1. 显示的说明参数来源
from fastapi import Depends, FastAPI, Path

app = FastAPI()

async def my_dependency_function(item_id: int = Path(...)):
    return {"item_id": item_id}


@app.get("/items/{item_id}")
async def read_item(my_dependency: dict = Depends(my_dependency_function):
    return my_dependency
  1. 将request对象作为参数
async def test_parameters(request:Request):
    vv = request
    return {"result":"success"}

@app.get('/ellis/parameters')
async def ellis(token:str=Depends(verify_jwt),value:dict=Depends(test_parameters)):
    return value
  1. 在路由层面设置dependends
items_router = APIRouter(
    prefix="/items",
    tags=["items"],
    dependencies=[Depends(my_dependency_function)],
)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值