| 1 |
""" |
| 2 |
Example of caching using aiocache package: |
| 3 |
|
| 4 |
/: Does a 3 seconds sleep. Only the first time because its using the `cached` decorator |
| 5 |
/reuse: Returns the data stored in "main" endpoint |
| 6 |
""" |
| 7 |
|
| 8 |
import asyncio |
| 9 |
|
| 10 |
from sanic import Sanic |
| 11 |
from sanic.response import json |
| 12 |
from sanic.log import logger |
| 13 |
from aiocache import cached, Cache |
| 14 |
from aiocache.serializers import JsonSerializer |
| 15 |
|
| 16 |
app = Sanic(__name__) |
| 17 |
|
| 18 |
|
| 19 |
@cached(key="my_custom_key", serializer=JsonSerializer()) |
| 20 |
async def expensive_call(): |
| 21 |
logger.info("Expensive has been called") |
| 22 |
await asyncio.sleep(3) |
| 23 |
return {"test": True} |
| 24 |
|
| 25 |
|
| 26 |
async def reuse_data(): |
| 27 |
cache = Cache(serializer=JsonSerializer()) # Not ideal to define here |
| 28 |
data = await cache.get("my_custom_key") # Note the key is defined in `cached` decorator |
| 29 |
return data |
| 30 |
|
| 31 |
|
| 32 |
@app.route("/") |
| 33 |
async def main(request): |
| 34 |
logger.info("Received GET /") |
| 35 |
return json(await expensive_call()) |
| 36 |
|
| 37 |
|
| 38 |
@app.route("/reuse") |
| 39 |
async def reuse(request): |
| 40 |
logger.info("Received GET /reuse") |
| 41 |
return json(await reuse_data()) |
| 42 |
|
| 43 |
|
| 44 |
app.run(host="0.0.0.0", port=8000) |