Flask-KVSession

https://travis-ci.org/mbr/flask-kvsession.svg?branch=master

Flask-KVSession is an MIT-licensed server-side session replacement for Flask‘s signed client-based session management. Instead of storing data on the client, only a securely generated ID is stored on the client, while the actual session data resides on the server.

This has two major advantages:

  • Clients no longer see the session information
  • It is possible to securely destroy sessions to protect against replay attacks.

Other things are possible with server side session that are impossible with clients side sessions, like inspecting and manipulating data in absence of the client.

Flask-KVSession uses the simplekv-package for storing session data on a variety of backends, including redis, memcached, SQL databases using SQLAlchemy, mongoDB or just flat files.

Integration with Flask is seamless, once the extension is loaded for a Flask application, it transparently replaces Flask’s own Session management. Any application working with sessions should work the same with Flask-KVSession (if it does not, file a bug!).

Documentation and development

Development happens on github, you can find the documentation on PyPI.

Example use

import redis
from flask import Flask
from flask_kvsession import KVSessionExtension
from simplekv.memory.redisstore import RedisStore

store = RedisStore(redis.StrictRedis())

app = Flask(__name__)
KVSessionExtension(store, app)

The snippet above will activate KVSession, from now on all session data will be stored in the KeyValueStore supplied to the KVSessionExtension constructor.

Expiring sessions

Sessions will expire, causing them to be invalid. To be automatically removed from the backend as well, that backend must support the TimeToLiveMixin interface; example backends that support this are are RedisStore and MemcacheStore.

When using a different backend without time-to-live support, for example flat files through FilesystemStore, cleanup_sessions() can be called periodically to remove unused sessions.

Namespacing sessions

Occasionally, it is handy to namespace session keys (for example, when sharing a Redis-database). This can be achieved using PrefixDecorator:

store = ...  # setup store normally
prefixed_store = PrefixDecorator('sessions_', store)

# ...

KVSessionExtension(prefixed_store, app)

The decorator will transparently prefix sessions_ to every session key stored and strip it upon retrieval.

Note

This requires simplekv>=0.9.2.

Configuration

In addition to SESSION_COOKIE_NAME and PERMANENT_SESSION_LIFETIME (see Flask documentation), the following configuration settings are available:

SESSION_KEY_BITS The size of the random integer to be used when generating random session ids. Defaults to 64.
SESSION_RANDOM_SOURCE Random source to use, defaults to an instance of random.SystemRandom.
SESSION_SET_TTL Whether or not to set the time-to-live of the session on the backend, if supported. Default is True.

API reference

flask_kvsession is a drop-in replacement module for Flask sessions that uses a simplekv.KeyValueStore as a backend for server-side sessions.

class flask_kvsession.KVSessionExtension(session_kvstore=None, app=None)

Activates Flask-KVSession for an application.

Parameters:
  • session_kvstore – An object supporting the simplekv.KeyValueStore interface that session data will be store in.
  • app – The app to activate. If not None, this is essentially the same as calling init_app() later.
cleanup_sessions(app=None)

Removes all expired session from the store.

Periodically, this function can be called to remove sessions from the backend store that have expired, as they are not removed automatically unless the backend supports time-to-live and has been configured appropriately (see TimeToLiveMixin).

This function retrieves all session keys, checks they are older than PERMANENT_SESSION_LIFETIME and if so, removes them.

Note that no distinction is made between non-permanent and permanent sessions.

Parameters:app – The app whose sessions should be cleaned up. If None, uses flask.current_app.
init_app(app, session_kvstore=None)

Initialize application and KVSession.

This will replace the session management of the application with Flask-KVSession’s.

Parameters:app – The Flask app to be initialized.
class flask_kvsession.SessionID(id, created=None)

Helper class for parsing session ids.

Internally, Flask-KVSession stores session ids that are serialized as KEY_CREATED, where KEY is a random number (the sessions “true” id) and CREATED a UNIX-timestamp of when the session was created.

Parameters:
  • id – An integer to be used as the session key.
  • created – A datetime instance or None. A value of None will result in utcnow() to be used.
has_expired(lifetime, now=None)

Report if the session key has expired.

Parameters:
serialize()

Serializes to the standard form of KEY_CREATED

classmethod unserialize(string)

Unserializes from a string.

Parameters:string – A string created by serialize().

Changes

Version 0.6.2

  • TTL support automatically detected
  • Various bugfixes

Version 0.5

  • Official Python3 support (now depends on simplekv >= 0.9 and six).
  • Major cleanup of documentation.
  • Includes support for sessions with limited time-to-live on the backend.

Version 0.4

  • No context is stored in the KVSessionExtension anymore. Instead, all data (including a refence to the actual store) is attached to the application.

    This means that a single KVSessionExtension can be used with multiple apps, if so desired, each with its own store.

  • Now requires Flask version >= 0.8, obsoleting some legacy version workarounds.

Version 0.3.2

  • Hotfix: Calling session.regenerate() on the first request should no longer cause an exception.

Version 0.3.1

  • Hotfix: Create empty KVSessions instead of NullSessions when a session is invalid or missing.

Version 0.3

  • Use pickle insteaed of json as the serialization method.
  • First occurence of changelog in docs.

Version 0.2

  • Complete rewrite.