Sessions

This module provides a lightweight but flexible session support for webapp2.

It has three built-in backends: secure cookies, memcache and datastore. New backends can be added extending CustomBackendSessionFactory.

The session store can provide multiple sessions using different keys, even using different backends in the same request, through the method SessionStore.get_session(). By default it returns a session using the default key from configuration.

webapp2_extras.sessions.default_config

Default configuration values for this module. Keys are:

secret_key
Secret key to generate session cookies. Set this to something random and unguessable. This is the only required configuration key: an exception is raised if it is not defined.
cookie_name
Name of the cookie to save a session or session id. Default is session.
session_max_age:
Default session expiration time in seconds. Limits the duration of the contents of a cookie, even if a session cookie exists. If None, the contents lasts as long as the cookie is valid. Default is None.
cookie_args

Default keyword arguments used to set a cookie. Keys are:

  • max_age: Cookie max age in seconds. Limits the duration of a session cookie. If None, the cookie lasts until the client is closed. Default is None.
  • domain: Domain of the cookie. To work accross subdomains the domain must be set to the main domain with a preceding dot, e.g., cookies set for .mydomain.org will work in foo.mydomain.org and bar.mydomain.org. Default is None, which means that cookies will only work for the current subdomain.
  • path: Path in which the authentication cookie is valid. Default is /.
  • secure: Make the cookie only available via HTTPS.
  • httponly: Disallow JavaScript to access the cookie.
backends
A dictionary of available session backend classes used by SessionStore.get_session().
class webapp2_extras.sessions.SessionStore(request, config=None)[source]

A session provider for a single request.

The session store can provide multiple sessions using different keys, even using different backends in the same request, through the method get_session(). By default it returns a session using the default key.

To use, define a base handler that extends the dispatch() method to start the session store and save all sessions at the end of a request:

import webapp2

from webapp2_extras import sessions

class BaseHandler(webapp2.RequestHandler):
    def dispatch(self):
        # Get a session store for this request.
        self.session_store = sessions.get_store(request=self.request)

        try:
            # Dispatch the request.
            webapp2.RequestHandler.dispatch(self)
        finally:
            # Save all sessions.
            self.session_store.save_sessions(self.response)

    @webapp2.cached_property
    def session(self):
        # Returns a session using the default cookie key.
        return self.session_store.get_session()

Then just use the session as a dictionary inside a handler:

# To set a value:
self.session['foo'] = 'bar'

# To get a value:
foo = self.session.get('foo')

A configuration dict can be passed to __init__(), or the application must be initialized with the secret_key configuration defined. The configuration is a simple dictionary:

config = {}
config['webapp2_extras.sessions'] = {
    'secret_key': 'my-super-secret-key',
}

app = webapp2.WSGIApplication([
    ('/', HomeHandler),
], config=config)

Other configuration keys are optional.

__init__(request, config=None)[source]

Initializes the session store.

Parameters:
  • request – A webapp2.Request instance.
  • config – A dictionary of configuration values to be overridden. See the available keys in default_config.
get_backend(name)[source]

Returns a configured session backend, importing it if needed.

Parameters:
  • name – The backend keyword.
Returns:

A BaseSessionFactory subclass.

get_session(name=None, max_age=<object object at 0x3e03b30>, factory=None, backend='securecookie')[source]

Returns a session for a given name. If the session doesn’t exist, a new session is returned.

Parameters:
  • name – Cookie name. If not provided, uses the cookie_name value configured for this module.
  • max_age – A maximum age in seconds for the session to be valid. Sessions store a timestamp to invalidate them if needed. If max_age is None, the timestamp won’t be checked.
  • factory – A session factory that creates the session using the preferred backend. For convenience, use the backend argument instead, which defines a backend keyword based on the configured ones.
  • backend

    A configured backend keyword. Available ones are:

    • securecookie: uses secure cookies. This is the default backend.
    • datastore: uses App Engine’s datastore.
    • memcache: uses App Engine’s memcache.
Returns:

A dictionary-like session object.

save_sessions(response)[source]

Saves all sessions in a response object.

Parameters:
  • response – A webapp.Response object.
class webapp2_extras.sessions.SessionDict(container, data=None, new=False)[source]

A dictionary for session data.

get_flashes(key='_flash')[source]

Returns a flash message. Flash messages are deleted when first read.

Parameters:
  • key – Name of the flash key stored in the session. Default is ‘_flash’.
Returns:

The data stored in the flash, or an empty list.

add_flash(value, level=None, key='_flash')[source]

Adds a flash message. Flash messages are deleted when first read.

Parameters:
  • value – Value to be saved in the flash message.
  • level – An optional level to set with the message. Default is None.
  • key – Name of the flash key stored in the session. Default is ‘_flash’.
class webapp2_extras.sessions.SecureCookieSessionFactory(name, session_store)[source]

A session factory that stores data serialized in a signed cookie.

Signed cookies can’t be forged because the HMAC signature won’t match.

This is the default factory passed as the factory keyword to SessionStore.get_session().

Warning

The values stored in a signed cookie will be visible in the cookie, so do not use secure cookie sessions if you need to store data that can’t be visible to users. For this, use datastore or memcache sessions.

class webapp2_extras.sessions.CustomBackendSessionFactory(name, session_store)[source]

Base class for sessions that use custom backends, e.g., memcache.

webapp2_extras.sessions.get_store(factory=<class 'webapp2_extras.sessions.SessionStore'>, key='webapp2_extras.sessions.SessionStore', request=None)[source]

Returns an instance of SessionStore from the request registry.

It’ll try to get it from the current request registry, and if it is not registered it’ll be instantiated and registered. A second call to this function will return the same instance.

Parameters:
  • factory – The callable used to build and register the instance if it is not yet registered. The default is the class SessionStore itself.
  • key – The key used to store the instance in the registry. A default is used if it is not set.
  • request – A webapp2.Request instance used to store the instance. The active request is used if it is not set.
webapp2_extras.sessions.set_store(store, key='webapp2_extras.sessions.SessionStore', request=None)[source]

Sets an instance of SessionStore in the request registry.

Parameters:
  • store – An instance of SessionStore.
  • key – The key used to retrieve the instance from the registry. A default is used if it is not set.
  • request – A webapp2.Request instance used to retrieve the instance. The active request is used if it is not set.

Previous topic

Security

Next topic

Configuration

This Page