alejcas / flask-session-plus

Flask Multiple Sessions Interface (combine multiple sessions with different backends)
MIT License
14 stars 7 forks source link
flask flask-extensions flask-session

Flask Multiple Sessions Interface

Combine multiple sessions with different backends

With Flask Session Plus you can use multiple different backends and choose what session variables are saved on what backend.

Python version:

It works on python >= 3.4 For the moment it should work on python 2.7 but it is not tested yet. If something does not work properly please open a bug report.

Install it with:

pip install flask-session-plus

For Flask Multi Session to work, all you have to do is define all your sessions on a simple configuration variable called SESSION_CONFIG, and init the extension.

Session Configuration Example:
# example using the Google Firestore backend
from google.cloud import firestore

SESSION_CONFIG = [
    # First session will store the csrf_token only on it's own cookie.
    {
        'cookie_name': 'csrf',
        'session_type': 'secure_cookie',
        'session_fields': ['csrf_token'],
    },
    # Second session will store the user logged in inside the firestore sessions collection.
    {
        'cookie_name': 'session',
        'session_type': 'firestore',
        'session_fields': ['user_id', 'user_data'],
        'client': firestore.Client(),
        'collection': 'sessions',
    },
    # Third session will store any other values set on the Flask session on it's own secure cookie
    {
        'cookie_name': 'data',
        'session_type': 'secure_cookie',
        'session_fields': 'auto'
    },
    # ... as many sessions as you want 
]

Caution: session_fields can collide if they have the same name and the same meaning. If they don't have the same meaning, you must use different field names.

The above configuration will define three session interfaces:

After configuring just register it as an extension:

from flask_session_plus import Session

app = Flask(__name__)

Session(app)

or

from flask_session_plus import Session

app = Flask(__name__)

session = Session()

session.init_app(app)

Current available backends:

More Backend Session Interfaces can be created by subclassing BackendSessionInterface and overwriting the following methods:

  1. __init__
  2. open_session
  3. save_session

All posible values for Session configuration: