Sessions

This module contains some helper classes that help one to add sessionsupport to a python WSGI application. For full client-side sessionstorage see securecookie which implements asecure, client-side session storage.

Application Integration

  1. from werkzeug.contrib.sessions import SessionMiddleware, \
  2. FilesystemSessionStore
  3. app = SessionMiddleware(app, FilesystemSessionStore())

The current session will then appear in the WSGI environment aswerkzeug.session. However it’s recommended to not use the middlewarebut the stores directly in the application. However for very simplescripts a middleware for sessions could be sufficient.

This module does not implement methods or ways to check if a session isexpired. That should be done by a cronjob and storage specific. Forexample to prune unused filesystem sessions one could check the modifiedtime of the files. It 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 thestore and session object directly in the application dispatching:

  1. session_store = FilesystemSessionStore()
  2. def application(environ, start_response):
  3. request = Request(environ)
  4. sid = request.cookies.get('cookie_name')
  5. if sid is None:
  6. request.session = session_store.new()
  7. else:
  8. request.session = session_store.get(sid)
  9. response = get_the_response_object(request)
  10. if request.session.should_save:
  11. session_store.save(request.session)
  12. response.set_cookie('cookie_name', request.session.sid)
  13. 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. Changesin mutable structures are not tracked, for those you have to setmodified to True by hand.

    • sid
    • The session ID as string.

    • new

    • True is the cookie was newly created, otherwise False

    • modified

    • Whenever an item on the cookie is set, this attribute is set to True.However this does not track modifications inside mutable objectsin the session:
  1. >>> c = Session({}, sid='deadbeefbabe2c00ffee')
  2. >>> c["foo"] = [1, 2, 3]
  3. >>> c.modified
  4. True
  5. >>> c.modified = False
  6. >>> c["foo"].append(4)
  7. >>> c.modified
  8. False

In that situation it has to be set to modified by hand so thatshould_save can pick it up.

  • should_save
  • True if the session should be saved.

在 0.6 版更改: By default the session is now only saved if the session ismodified, 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 notimplement any useful stores besides the filesystem store, applicationdevelopers are encouraged to create their own stores.

参数:session_class – The session class to use. Defaults toSession.

  • delete(session)
  • Delete a session.

  • generatekey(_salt=None)

  • Simple function that generates a new session key.

  • get(sid)

  • Get a session for this sid or a new session object. This methodhas to check if the session key is valid and create a new session ifthat wasn’t the case.

  • isvalid_key(_key)

  • Check if a key has the correct format.

  • new()

  • Generate a new session.

  • save(session)

  • Save a session.

  • saveif_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 / WindowsServer 2008 and newer.

在 0.6 版更改: renew_missing was added. Previously this was considered True,now the default changed to False and it can be explicitlydeactivated.

参数:

  • 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 sessiona filename. %s is replaced with thesession id.
  • session_class – The session class to use. Defaults toSession.
  • renew_missing – set to True if you want the store togive the user a new sid if the session wasnot yet saved.
  • list()
  • Lists all sessions in the store.

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, environ_key='werkzeug.session')
  • A simple middleware that puts the session object of a store providedinto the WSGI environ. It automatically sets cookies and restoressessions.

However a middleware is not the preferred solution because it won’t be asfast as sessions managed by the application itself and will put a key intothe WSGI environment only relevant for the application which is againstthe concept of WSGI.

The cookie parameters are the same as for the dumpcookie()function just prefixed with cookie. Additionally max_age iscalled cookie_age and not cookie_max_age because of backwardscompatibility.