[Python] How to set cookies on Jinja2 TemplateResponse in FastAPI?

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

  1. Stack

    Stack Membro Participativo

    I am using Python FastAPI and Jinja2, all of which I am new to. I am able to set cookies alone or return html templates on their own, but I cannot work out how to do both at once.

    Setting cookies only works as expected, but returning a template seems to overwrite that and just returns html with no cookies.

    @app.get("/oauth/auth", response_class=HTMLResponse)
    async def login_page(request: Request, response: Response):
    client_Code_Req_Schema = ClientCodeReqSchema(client_id=request.query_params.get("client_id"), redirect_uri=request.query_params.get("redirect_uri"), response_type=request.query_params.get("response_type"))
    if check_client(client_Code_Req_Schema):
    response.set_cookie(key="redirect_uri", value="test")
    return templates.TemplateResponse("authorize.html", {"request": request})
    else:
    raise HTTPException(status_code=400, detail="Invalid request")


    Many thanks for any advice. Happy to provide more info if I missed something.

    Continue reading...

Compartilhe esta Página