1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
import time
from typing import AsyncIterator
from aiohttp import web
from redis import asyncio as aioredis
from aiohttp_session import get_session, setup
from aiohttp_session.redis_storage import RedisStorage
async def handler(request: web.Request) -> web.Response:
session = await get_session(request)
last_visit = session["last_visit"] if "last_visit" in session else None
session["last_visit"] = time.time()
text = f"Last visited: {last_visit}"
return web.Response(text=text)
async def redis_pool(app: web.Application) -> AsyncIterator[None]:
redis_address = "redis://127.0.0.1:6379"
async with aioredis.from_url(redis_address) as redis: # type: ignore[no-untyped-call]
storage = RedisStorage(redis)
setup(app, storage)
yield
def make_app() -> web.Application:
app = web.Application()
app.cleanup_ctx.append(redis_pool)
app.router.add_get("/", handler)
return app
web.run_app(make_app())
|