[Python] FastAPI/Starlette's Request object is empty when used in a normal function

Discussão em 'Python' iniciado por Stack, Março 22, 2025.

  1. Stack

    Stack Membro Participativo

    When I use request inside a FastAPI route, the request is filled with the proper headers, such as:

    request.headers.get('X-Forwarded-For')


    However, when I use the request object inside a function, which isn't a route, all the values are empty. I guess the whole object is not evaluated?

    Working:

    from fastapi import Request


    @app.get("/logip")
    async def log_request_ip(request: Request):
    print(request.headers.get("X-Forwarded-For))


    Not working:

    from fastapi import Request


    @app.get("/logip")
    async def log_request_ip():
    log_ip()


    def log_ip(request: Request = Request):
    print(request.headers.get("X-Forwarded-For))


    Is there a reason for this? Does FastAPI only evaluate the request object when it is injected into the route, but not in a function? Is there any way to make this possible? I want to avoid injecting the request into every route, and just keep this in the function that actually uses this value.

    Is there maybe a way to tell FastAPI that this function is only used within a request context?

    Continue reading...

Compartilhe esta Página