Flask-KVSession¶
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:
|
The size of the random integer to be used when generating random session ids. Defaults to 64. |
|
Random source to use, defaults to an instance of
|
|
Whether or not to set the time-to-live of the
session on the backend, if supported. Default
is |
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.KVSession(initial=None)¶
- destroy()¶
Destroys a session completely, by deleting all keys and removing it from the internal store immediately.
This allows removing a session for security reasons, e.g. a login stored in a session will cease to exist if the session is destroyed.
- modified = False¶
Replacement session class.
Instances of this class will replace the session (and thus be available through things like
flask.session
.The session class will save data to the store only when necessary, empty sessions will not be stored at all.
- regenerate()¶
Generate a new session id for this session.
To avoid vulnerabilities through session fixation attacks, this function can be called after an action like a login has taken place. The session will be copied over to a new session id and the old one removed.
- 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
flask.Flask.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
, usescurrent_app
.
- clear_all_sessions(app=None)¶
Removes all session from the store.
This function retrieves all session keys, 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
, usescurrent_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.KVSessionInterface¶
- open_session(app, request)¶
This method has to be implemented and must either return
None
in case the loading failed because of a configuration error or an instance of a session object which implements a dictionary like interface + the methods and attributes onSessionMixin
.
- save_session(app, session, response)¶
This is called for actual sessions returned by
open_session()
at the end of the request. This is still called during a request context so if you absolutely need access to the request you can do that.
- serialization_method = <module 'pickle' from '/usr/lib/python3.10/pickle.py'>¶
- session_class¶
alias of
flask_kvsession.KVSession
- 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
, whereKEY
is a random number (the sessions “true” id) andCREATED
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 inutcnow()
to be used.
- has_expired(lifetime, now=None)¶
Report if the session key has expired.
- Parameters
lifetime – A
datetime.timedelta
that specifies the maximum age thisSessionID
should be checked against.now – If specified, use this
datetime
instance instead ofutcnow()
as the current time.
- 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.3¶
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.