Reference

Public functions

aiohttp_session.get_session(request)[source]

A coroutine for getting session instance from request object.

See example below in Session section for get_session() usage.

aiohttp_session.session_middleware(storage)[source]

Session middleware factory.

Create session middleware to pass into aiohttp.web.Application constructor.

storage is a session storage instance (object used to store session data into cookies, Redis, database etc., class is derived from AbstractStorage).

See also

Session storages

Note

setup() is new-fashion way for library setup.

aiohttp_session.setup(app, storage)[source]

Setup session support for given app.

The function is shortcut for:

app.middlewares.append(session_middleware(storage))

app is aiohttp.web.Application instance.

storage is a session storage instance (object used to store session data into cookies, Redis, database etc., class is derived from AbstractStorage).

See also

Session storages

Session

class aiohttp_session.Session[source]

Client’s session, a namespace that is valid for some period of continual activity that can be used to represent a user’s interaction with a web application.

Warning

Never create Session instances by hands, retieve those by get_session() call.

The Session is a MutableMapping, thus it supports all dictionary methods, along with some extra attributes and methods:

from aiohttp_session import get_session

@asyncio.coroutine
def handler(request):
    session = yield from get_session(request)
    session['key1'] = 'value 1'
    assert 'key2' in session
    assert session['key2'] == 'value 2'
    # ...
created

Creation UNIX TIMESTAMP, the value returned by time.time() for very first access to the session object.

identity

Client’s identity. It may be cookie name or database key. Read-only property.

new

A boolean. If new is True, this session is new. Otherwise, it has been constituted from data that was already serialized.

changed()[source]

Call this when you mutate a mutable value in the session namespace. See the note below for details on when, and why you should call this.

Note

Keys and values of session data must be pickleable. This means, typically, that they are instances of basic types of objects, such as strings, lists, dictionaries, tuples, integers, etc. If you place an object in a session data key or value that is not pickleable, an error will be raised when the session is serialized.

If you place a mutable value (for example, a list or a dictionary) in a session object, and you subsequently mutate that value, you must call the changed() method of the session object. In this case, the session has no way to know that is was modified. However, when you modify a session object directly, such as setting a value (i.e., __setitem__), or removing a key (e.g., del or pop), the session will automatically know that it needs to re-serialize its data, thus calling changed() is unnecessary. There is no harm in calling changed() in either case, so when in doubt, call it after you’ve changed sessioning data.

invalidate()[source]

Call this when you want to invalidate the session (dump all data, and – perhaps – set a clearing cookie).

Session storages

aiohttp_session uses storages to save/load persistend session data.

Abstract Storage

All storages should be derived from AbstractStorage and implement both load_session() and save_session() methods.

class aiohttp_session.AbstractStorage(cookie_name="AIOHTTP_SESSION", *, domain=None, max_age=None, path='/', secure=None, httponly=True)[source]

Base class for session storage implementations.

It uses HTTP cookie for storing at least the key for session data, but some implementations may save all session info into cookies.

cookie_name – name of cookie used for saving session data.

domain – cookie’s domain, str or None.

max_age – cookie’s max age, int or None.

path – cookie’s path, str or None.

secure – cookie’s secure flag, bool or None (the same as False).

httponly – cookie’s http-only flag, bool or None (the same as False).

max_age

Maximum age for session data, int seconds or None for “session cookie” which last until you close your browser.

cookie_name

Name of cookie used for saving session data.

cookie_params

dict of cookie params: domain, max_age, path, secure and httponly.

load_session(request)[source]

An abstract coroutine, called by internal machinery for retrieving Session object for given request (aiohttp.web.Request instance).

Return Session instance.

save_session(request, response, session)[source]

An abstract coroutine, called by internal machinery for storing session (Session) instance for given request (aiohttp.web.Request) using response (aiohttp.web.StreamResponse or descendants).

A helper for loading cookie (http.cookies.SimpleCookie instance) from request (aiohttp.web.Request).

A helper for saving cookie_data (str) into response (aiohttp.web.StreamResponse or descendants).

max_age is cookie lifetime given from session. Storage defailt is used if the value is None.

Simple Storage

For testing purposes there is SimpleCookieStorage. It stores session data as unencrypted and unsigned JSON data in browser cookies, so it’s totally insecure.

Warning

Never use this storage on production!!! It’s highly insecure!!!

To use the storage you should push it into session_middleware():

app = aiohttp.web.Application(
    middlewares=[aiohttp_session.SimpleCookieStorage()])
class aiohttp_session.SimpleCookieStorage(*, cookie_name="AIOHTTP_SESSION", domain=None, max_age=None, path='/', secure=None, httponly=True)[source]

Create unencrypted cookie storage.

The class is inherited from AbstractStorage.

Parameters are the same as for AbstractStorage constructor.

NaCl Storage

The storage that saves session data in HTTP cookies as SecretBox encrypted data.

To use the storage you should push it into session_middleware():

app = aiohttp.web.Application(middlewares=[
    aiohttp_session.cookie_storage.NaClCookieStorage(
        b'Thirty  two  length  bytes  key.'])
class aiohttp_session.cookie_storage.NaClCookieStorage(secret_key, *, cookie_name="AIOHTTP_SESSION", domain=None, max_age=None, path='/', secure=None, httponly=True)

Create encryted cookies storage.

The class is inherited from AbstractStorage.

secret_key is bytes secret key with length of 32, used for encoding.

Other parameters are the same as for AbstractStorage constructor.

Redis Storage

The storage that stores session data in Redis database and keeps only Redis keys (UUIDs actually) in HTTP cookies.

It operates with Redis database via aioredis.RedisPool.

To use the storage you need setup it first:

redis = yield from aioredis.create_pool(('localhost', 6379))
storage = aiohttp_session.redis_storage.RedisStorage(redis)
session_middleware = aiohttp_session.session_middleware(storage)
app = aiohttp.web.Application(middlewares=[session_middleware])
class aiohttp_session.redis_storage.RedisStorage(redis_pool, *, cookie_name="AIOHTTP_SESSION", domain=None, max_age=None, path='/', secure=None, httponly=True)[source]

Create Redis storage for user session data.

The class is inherited from AbstractStorage.

redis_pool is a RedisPool which should be created by create_pool() call, e.g.:

redis = yield from aioredis.create_pool(('localhost', 6379))
storage = aiohttp_session.redis_storage.RedisStorage(redis)

Other parameters are the same as for AbstractStorage constructor.