[Python] Session object in FastAPI similar to Flask

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

  1. Stack

    Stack Membro Participativo

    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)

    Continue reading...

Compartilhe esta Página