[Python] How to add a middleware before the application starts up in FastAPI?

Discussão em 'Python' iniciado por Stack, Setembro 29, 2024.

  1. Stack

    Stack Membro Participativo

    Using Lifespan Events and Middleware, I would like to add a middleware inside an asynccontextmanager (at application startup). It should look something like this:

    @asynccontextmanager
    async def lifespan(app: FastAPI):
    if some_condition:
    @app.middleware("http")
    async def my_middleware(request: Request, call_next):
    response = await call_next(request)
    return response
    yield
    pass


    app = FastAPI(lifespan=lifespan)


    However, the example above raises the following error:

    RuntimeError: Cannot add middleware after an application has started


    But, in the beginning of Lifespan Events documentation, it is mentioned that:


    You can define logic (code) that should be executed before the application starts up. This means that this code will be executed once, before the application starts receiving requests.
    ​

    How should I approach this?

    Continue reading...

Compartilhe esta Página