Sessions
Warning
Deprecated since version 0.15: This will be removed in version 1.0. It has moved to https://github.com/pallets/secure-cookie.
werkzeug.contrib.sessions
This module contains some helper classes that help one to add session support to a python WSGI application. For full client-side session storage see securecookie which implements a secure, client-side session storage.
Application Integration
from werkzeug.contrib.sessions import SessionMiddleware, \
FilesystemSessionStore
app = SessionMiddleware(app, FilesystemSessionStore())
The current session will then appear in the WSGI environment as werkzeug.session. However it’s recommended to not use the middleware but the stores directly in the application. However for very simple scripts a middleware for sessions could be sufficient.
This module does not implement methods or ways to check if a session is expired. That should be done by a cronjob and storage specific. For example to prune unused filesystem sessions one could check the modified time of the files. If sessions are stored in the database the new() method should add an expiration timestamp for the session.
For better flexibility it’s recommended to not use the middleware but the store and session object directly in the application dispatching:
session_store = FilesystemSessionStore()
def application(environ, start_response):
request = Request(environ)
sid = request.cookies.get('cookie_name')
if sid is None:
request.session = session_store.new()
else:
request.session = session_store.get(sid)
response = get_the_response_object(request)
if request.session.should_save:
session_store.save(request.session)
response.set_cookie('cookie_name', request.session.sid)
return response(environ, start_response)
Reference
-
class werkzeug.contrib.sessions.Session(data, sid, new=False) -
Subclass of a dict that keeps track of direct object changes. Changes in mutable structures are not tracked, for those you have to set
modifiedtoTrueby hand.-
sid -
The session ID as string.
-
new -
Trueis the cookie was newly created, otherwiseFalse
-
modified -
Whenever an item on the cookie is set, this attribute is set to
True. However this does not track modifications inside mutable objects in the session:>>> c = Session({}, sid='deadbeefbabe2c00ffee') >>> c["foo"] = [1, 2, 3] >>> c.modified True >>> c.modified = False >>> c["foo"].append(4) >>> c.modified FalseIn that situation it has to be set to
modifiedby hand so thatshould_savecan pick it up.
-
should_save -
True if the session should be saved.
Changed in version 0.6: By default the session is now only saved if the session is modified, not if it is new like it was before.
-
-
class werkzeug.contrib.sessions.SessionStore(session_class=None) -
Baseclass for all session stores. The Werkzeug contrib module does not implement any useful stores besides the filesystem store, application developers are encouraged to create their own stores.
Parameters: session_class – The session class to use. Defaults to Session.-
delete(session) -
Delete a session.
-
generate_key(salt=None) -
Simple function that generates a new session key.
-
get(sid) -
Get a session for this sid or a new session object. This method has to check if the session key is valid and create a new session if that wasn’t the case.
-
is_valid_key(key) -
Check if a key has the correct format.
-
new() -
Generate a new session.
-
save(session) -
Save a session.
-
save_if_modified(session) -
Save if a session class wants an update.
-
-
class werkzeug.contrib.sessions.FilesystemSessionStore(path=None, filename_template='werkzeug_%s.sess', session_class=None, renew_missing=False, mode=420) -
Simple example session store that saves sessions on the filesystem. This store works best on POSIX systems and Windows Vista / Windows Server 2008 and newer.
Changed in version 0.6:
renew_missingwas added. Previously this was consideredTrue, now the default changed toFalseand it can be explicitly deactivated.Parameters: - path – the path to the folder used for storing the sessions. If not provided the default temporary directory is used.
-
filename_template – a string template used to give the session a filename.
%sis replaced with the session id. -
session_class – The session class to use. Defaults to
Session. -
renew_missing – set to
Trueif you want the store to give the user a new sid if the session was not yet saved.
-
list() -
Lists all sessions in the store.
New in version 0.6.
-
class werkzeug.contrib.sessions.SessionMiddleware(app, store, cookie_name='session_id', cookie_age=None, cookie_expires=None, cookie_path='/', cookie_domain=None, cookie_secure=None, cookie_httponly=False, cookie_samesite='Lax', environ_key='werkzeug.session') -
A simple middleware that puts the session object of a store provided into the WSGI environ. It automatically sets cookies and restores sessions.
However a middleware is not the preferred solution because it won’t be as fast as sessions managed by the application itself and will put a key into the WSGI environment only relevant for the application which is against the concept of WSGI.
The cookie parameters are the same as for the
dump_cookie()function just prefixed withcookie_. Additionallymax_ageis calledcookie_ageand notcookie_max_agebecause of backwards compatibility.
© 2007–2020 Pallets
Licensed under the BSD 3-clause License.
https://werkzeug.palletsprojects.com/en/0.16.x/contrib/sessions/