aiohttp_session¶
The library provides sessions for aiohttp.web.
The current version is 2.12
Usage¶
The library allows to store user-specific data into session object.
The session object has dict-like interface (operations like
session[key] = value
or value = session[key]
etc. are supported).
Before processing session in web-handler you have to register session
middleware in aiohttp.web.Application
.
A trivial usage example:
import time
from aiohttp import web
from aiohttp_session import get_session, setup
from aiohttp_session.cookie_storage import EncryptedCookieStorage
async def handler(request):
session = await get_session(request)
session['last_visit'] = time.time()
return web.Response(text='OK')
def init():
app = web.Application()
setup(app,
EncryptedCookieStorage(b'Thirty two length bytes key.'))
app.router.add_route('GET', '/', handler)
return app
web.run_app(init())
All storages uses HTTP Cookie named AIOHTTP_COOKIE_SESSION
for storing data.
Available session storages are:
SimpleCookieStorage
– keeps session data as plain JSON string in cookie body. Use the storage only for testing purposes, it’s very non-secure.EncryptedCookieStorage
– stores session data into cookies likeSimpleCookieStorage
does but encodes the data via cryptography Fernet cipher.For key generation use
cryptography.fernet.Fernet.generate_key()
method.Requires cryptography library:
$ pip3 install aiohttp_session[secure]
RedisStorage
– stores JSON-ed data into redis, keeping into cookie only redis key (random UUID).Inside redis the key will be saved as COOKIENAME_VALUEOFTHECOOKIE. For example if inside the browser the cookie is saved with name
'AIOHTTP_SESSION'
(default option) and valuee33b57c7ec6e425eb626610f811ab6ae
(a random UUID) they key inside redis will beAIOHTTP_SESSION_e33b57c7ec6e425eb626610f811ab6ae
.Requires redis library:
$ pip install aiohttp_session[aioredis]
MemcachedStorage
– the same as Redis storage but uses Memcached database.Requires aiomcache library:
$ pip install aiohttp_session[aiomcache]
Installation¶
$ pip3 install aiohttp_session
Source code¶
The project is hosted on GitHub
Please feel free to file an issue on bug tracker if you have found a bug or have some suggestion for library improvement.
The library uses Travis for Continuous Integration.
Dependencies¶
- cryptography for
EncryptedCookieStorage
- redis for
RedisStorage