Flask-Session not persisting across routes when using SqlAlchemySessionInterface

41 views Asked by At

I am trying to create an application with Flask and React. I want to use the SqlAlchemySessionInterface because the application is using Postgres.

The issue I am facing is that the session isn't getting saved in the db, even though the table is created. When the login request is sent, the session is created and show the users id. But when I make a call to get the user, the session variable is empty.

What could be a possible cause for this?

What I have:

from flask import Flask, redirect, jsonify, request, session
from flask_session import SqlAlchemySessionInterface

app = Flask(__name__)

bcrypt = Bcrypt(app)
CORS(app)
db = SQLAlchemy(app)
db.init_app(app)

SqlAlchemySessionInterface(app, db, table="sessions", key_prefix="sess_", use_signer=True)

... 

@app.before_first_request
def create_tables(): 
    with app.app_context():
        db.create_all()
        db.session.commit()

@app.route('/login', methods=['POST'])
def login_test():
    user_req = request.get_json()['form']

    user = User.query.filter_by(email=user_req['email']).first()

    if user and bcrypt.check_password_hash(user.password, user_req['password']):
        session['user_id']=user.id

        response = make_response({
            'user': session.get('user_id')
        })
        response.headers['Access-Control-Allow-Credentials'] = 'true'

        
        return response
    
    return {
        'error': 'error'
    }

@app.route("/@me", methods=['POST'])
def get_current_user():
    print(request.method)
    response = make_response({
            'user': session.get('user_id')
    })
    response.headers['Access-Control-Allow-Credentials'] = 'true'

    return response

The result: A request to the /login route verifies the user exists, add to the session and return the user_id as it should. But a request to the /@me route returns null.

0

There are 0 answers