简体   繁体   中英

Inject parameter to every route of an APIRouter using FastAPI

With FastAPI's APIRouter , I know you can pass a dependency through the dependencies parameter. Every example I see though has a dependency that doesn't return anything. I've been diving through the code, but I'm guessing I'm not understanding how to do what I want, and would be fine knowing that is not possible; I can always add the dependency to every route.

my_module = APIRouter(prefix="/abc", dependencies=[Depends(get_permissions)])

@my_module.get('/')
def route_1(permissions: Permissions):
    pass

@my_module.get('/a')
def route_2(permissions: Permissions):
    pass

I want to do something like this where the permissions are retrieved via get_permissions and injected into each route.

The way around this issue is to store the returned value to request.state , as described in this answer (see State implementation):

from fastapi import Request

def get_permissions(request: Request):
    request.state.my_attr = 'some value'
    # ...

Afterwards, inside the endpoints, you can retrieve that attribute, as described in this answer and as shown below:

router = APIRouter(prefix='/abc', dependencies=[Depends(get_permissions)])

@router.get('/')
def route_1(request: Request):
    return request.state.my_attr

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM