CI / Build Pip package (push) Successful in 1m56s
- Move src/kaya/session_redis/ → src/kaya/session/redis/ - Update pyproject.toml version_file path - Update all import references (tests, READMEs, root README)
51 lines
1.4 KiB
Markdown
51 lines
1.4 KiB
Markdown
# kaya-session-redis
|
|
|
|
Redis-backed session storage for the Kaya web framework.
|
|
|
|
Provides `RedisSessionStore`, a `SessionStore` implementation (from
|
|
`kaya-session`) that persists session data in Redis, so sessions are shared
|
|
across processes and hosts.
|
|
|
|
## Usage
|
|
|
|
```python
|
|
from redis.asyncio import Redis
|
|
|
|
from kaya.core import KayaApp, HttpContext
|
|
from kaya.session import SessionMixin
|
|
from kaya.session.redis import RedisSessionStore
|
|
|
|
client = Redis(host='localhost', port=6379)
|
|
session = SessionMixin(RedisSessionStore(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 Redis key TTLs and slides
|
|
on each access when the session mixin passes a `max_age`.
|
|
|
|
## 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 = RedisSessionStore(
|
|
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 Redis server.
|