[FIXED] flask-session: how to create the session table

Issue

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?

Solution

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

Answered By – Mekicha

Answer Checked By – Dawn Plyler (FixeMe Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *