53 lines
1.6 KiB
Markdown
53 lines
1.6 KiB
Markdown
# kaya-session-memcache
|
|
|
|
Memcached-backed session storage for the Kaya web framework.
|
|
|
|
Provides `MemcacheSessionStore`, a `SessionStore` implementation (from
|
|
`kaya-session`) that persists session data in memcached via `aiomcache`, so
|
|
sessions are shared across processes and hosts.
|
|
|
|
## Usage
|
|
|
|
```python
|
|
import aiomcache
|
|
|
|
from kaya.core import KayaApp, HttpContext
|
|
from kaya.session import SessionMixin
|
|
from kaya.session_memcache import MemcacheSessionStore
|
|
|
|
client = aiomcache.Client('127.0.0.1', 11211)
|
|
session = SessionMixin(MemcacheSessionStore(client))
|
|
app = KayaApp(mixins=[session])
|
|
|
|
@app.GET('/')
|
|
async def home(ctx: HttpContext):
|
|
n = ctx.session.get('visits', 0) + 1
|
|
ctx.session['visits'] = n
|
|
await ctx.send_str(200, f'visits: {n}')
|
|
```
|
|
|
|
Sessions are stored under keys with the prefix `kaya:session:` (configurable
|
|
via the `prefix` argument). Server-side expiry uses memcached item expiration
|
|
and slides on each access when the session mixin passes a `max_age`. TTLs
|
|
larger than 30 days are automatically converted to absolute Unix timestamps,
|
|
as required by the memcached protocol.
|
|
|
|
## Serialization
|
|
|
|
Session data is serialized with `pickle` by default, so arbitrary Python
|
|
objects can be stored. A different serializer can be plugged in via the
|
|
`dumps`/`loads` arguments:
|
|
|
|
```python
|
|
import json
|
|
|
|
store = MemcacheSessionStore(
|
|
client,
|
|
dumps=lambda d: json.dumps(d).encode('utf-8'),
|
|
loads=lambda b: json.loads(b.decode('utf-8')),
|
|
)
|
|
```
|
|
|
|
**Warning:** pickle deserialization of untrusted data is unsafe. Only use the
|
|
default serializer with a trusted memcached server.
|