session object in Fastapi similar to flask

Question:

I am trying to use session to pass variables across view functions in fastapi. However, I do not find any doc which specifically says of about session object. Everywhere I see, cookies are used. Is there any way to convert the below flask code in fastapi? I want to keep session implementation as simple as possible.

from flask import Flask, session, render_template, request, redirect, url_for


app=Flask(__name__)
app.secret_key='asdsdfsdfs13sdf_df%&'   

@app.route('/a')
def a():
    session['my_var'] = '1234'              
    return redirect(url_for('b'))          


@app.route('/b')
def b():
    my_var = session.get('my_var', None)
    return my_var    


if __name__=='__main__':
    app.run(host='0.0.0.0', port=5000, debug = True)
Asked By: myquest2 sh

||

Answers:

Take a look at Starlette’s SessionMiddleware. FastAPI uses Starlette under the hood so it is compatible.

After you register SessionMiddleware, you can access Request.session, which is a dictionary.

Documentation: SessionMiddleware

An implementation in FastAPI may look like:

@app.route("/a")
async def a(request: Request) -> RedirectResponse:

    request.session["my_var"] = "1234"

    return RedirectResponse("/b")

@app.route("/b")
async def b(request: Request) -> PlainTextResponse:

    my_var = request.session.get("my_var", None)

    return PlainTextResponse(my_var)
Answered By: user17815749
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.