Flask Sessions: How to store both sessions and permanent data in the same database?

231 Views Asked by At

I would like to store session-related data using flask_session and flask_sqlalchemy. I would also like to store data in the same database but other tables that should not be dependent on the browser's session.

The app.py code below will not run, due to the following error

"sqlalchemy.exc.InvalidRequestError: Table 'sessions' is already defined for this MetaData instance. Specify 'extend_existing=True' to redefine options and columns on an existing Table object.”

The sessions table will be created in the database if I don't try to create the other tables (classes that extend db.Model). On the hand, the db.Models tables will be created if don't use the sessions of Flask_Session. If I assign 'filesystem' to a session-type I get the server-side sessions in the file system as expected.

I would appreciate if someone here could give me some advice on how to get both to work.

from flask import Flask
from flask_session import Session
import os
from dotenv import load_dotenv

def create_app():
    from database.db_models import db # where my models are defined
    app = Flask(__name__)
    app.secret_key="MY_SECRET_KEY"
    load_dotenv()
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://my_user_name:my_pw@localhost/db_name?auth_plugin=mysql_native_password'
    app.config['SESSION_TYPE'] = 'sqlalchemy'
    # Configure Flask-Session
    
    
    app.config['SESSION_SQLALCHEMY'] = db
    db.init_app(app)
    
    Session(app)
    
    with app.app_context():
        db.create_all()
    return app
    
       
host = '0.0.0.0'
port = 8080
app = create_app()



if __name__== "__main__":
    app.run(host='0.0.0.0',port=port)
    
    
    

I tried using sqlalchemy directly (not flask_sqlalchemy). This didn't work as it seems like flask_session uses flask_sqlalchemy.

1

There are 1 best solutions below

0
user22170052 On

It turned out that my create_app was called more than once. After the first time it was called because I imported app to other modules. I figured out that Flask provides a reference to the app called current_app that helps to avoid this situation.

This was found here.

I hope I could save some time for those who had a similar situation.