| 1 |
import asyncio |
| 2 |
import logging |
| 3 |
from datetime import datetime |
| 4 |
from aiohttp import web |
| 5 |
from aiocache import cached |
| 6 |
from aiocache.serializers import JsonSerializer |
| 7 |
|
| 8 |
|
| 9 |
@cached(key="function_key", serializer=JsonSerializer()) |
| 10 |
async def time(): |
| 11 |
return {"time": datetime.now().isoformat()} |
| 12 |
|
| 13 |
|
| 14 |
async def handle(request): |
| 15 |
return web.json_response(await time()) |
| 16 |
|
| 17 |
|
| 18 |
# It is also possible to cache the whole route, but for this you will need to |
| 19 |
# override `cached.get_from_cache` and regenerate the response since aiohttp |
| 20 |
# forbids reusing responses |
| 21 |
class CachedOverride(cached): |
| 22 |
def __init__(self, *args, **kwargs): |
| 23 |
super().__init__(*args, **kwargs) |
| 24 |
|
| 25 |
async def get_from_cache(self, key): |
| 26 |
try: |
| 27 |
value = await self.cache.get(key) |
| 28 |
if type(value) == web.Response: |
| 29 |
return web.Response( |
| 30 |
body=value.body, |
| 31 |
status=value.status, |
| 32 |
reason=value.reason, |
| 33 |
headers=value.headers, |
| 34 |
) |
| 35 |
return value |
| 36 |
except Exception: |
| 37 |
logging.exception("Couldn't retrieve %s, unexpected error", key) |
| 38 |
return None |
| 39 |
|
| 40 |
|
| 41 |
@CachedOverride(key="route_key", serializer=JsonSerializer()) |
| 42 |
async def handle2(request): |
| 43 |
return web.json_response(await asyncio.sleep(3)) |
| 44 |
|
| 45 |
|
| 46 |
if __name__ == "__main__": |
| 47 |
app = web.Application() |
| 48 |
app.router.add_get('/handle', handle) |
| 49 |
app.router.add_get('/handle2', handle2) |
| 50 |
|
| 51 |
web.run_app(app) |