flask-session: how to create the session table

旧时模样 提交于 2019-12-21 22:42:10

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/45887266/flask-session-how-to-create-the-session-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!