I'm trying to enable server-side sessions for my flask application using a SQLite database. Note I'm using Flask-Sessionstore which is a hard fork of Flask-Session and is more actively maintained. However, I'm getting the same error when I use both libraries. Here is my code for app.py
:
from flask import Flask, session
from flask_sqlalchemy import SQLAlchemy
from flask_sessionstore import Session
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////Users/Johnny/DBs/test.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # quiet warning message
app.config['SESSION_TYPE'] = 'sqlalchemy'
Session(app)
@app.route('/')
def index():
return 'Hello World!'
if __name__ == '__main__':
app.run(debug=True)
When I run the application with python app.py
everything starts and runs as expected. However, when I try to access the index page at http://127.0.0.1:5000 I get the following error:
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: sessions [SQL: 'SELECT sessions.id AS sessions_id, sessions.session_id AS sessions_session_id, sessions.data AS sessions_data, sessions.expiry AS sessions_expiry \nFROM sessions \nWHERE sessions.session_id = ?\n LIMIT ? OFFSET ?'] [parameters: ('session:xxx...', 1, 0)]
It appears I need to create this table before running the application. How can I do this? Or am I missing a configuration option that creates the table for me if it's not found?
You will need to provide this in your app config as well:
app.config[SESSION_SQLALCHEMY_TABLE] = 'sessions'
app.config[SESSION_SQLALCHEMY] = db
where db
is sqlAlchemy instance. So you should have something like:
db = SQLAlchemy(app)
session = Session(app)
session.app.session_interface.db.create_all()
You can take a look at the test example of flask_sessionstore on github
The answer from @Mekicha works but if you already have your database and don't want to run db.create_all()
, consider this alternative:
After you initialize your session instance with the app, you can use the sqlalchemy interface to build your 'session' table, if none is existent:
SqlAlchemySessionInterface(app, db, "sessions", "sess_")
Then run a migration against your database.
See this related post for a full example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With