Your Ad could be here. I want to connect my readers to relavant ads. If you have a product targeted at developers, let's talk. [email protected]

Here's my thought on FastAPI - dependency inside Middleware? - Stack Overflow

After struggling to get dependencies inside of middleware I learned that you can make global dependencies at the app level. I used this to set the user on every single route of the application without needing Depend on getting the user on each route.

from fastapi import Depends, FastAPI, Request

def get_db_session():
    print("Calling 'get_db_session(...)'")
    return "Some Value"

def get_current_user(session=Depends(get_db_session)):
    print("Calling 'get_current_user(...)'")
    return session

def recalculate_resources(request: Request, current_user=Depends(get_current_user)):
    print("calling 'recalculate_resources(...)'") = current_user

app = FastAPI(dependencies=[Depends(recalculate_resources)])

async def root(request: Request):
    return {"foo_from_dependency":}

This post was a thought by Waylon Walker see all my thoughts at