Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flask-session: how to create the session table

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?

like image 538
Johnny Metz Avatar asked Jan 04 '23 13:01

Johnny Metz


2 Answers

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

like image 86
Mekicha Avatar answered Jan 13 '23 14:01

Mekicha


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

like image 21
kip2 Avatar answered Jan 13 '23 14:01

kip2