Caching example using aiocache (#140)

* Keep-alive requests stay open if communicating

* time.time faster than loop.time?

* Fix flake8

* Add aiofiles to requirements.txt

* Caching example using aiocache

* Caching example using aiocache

* Added aiocache to requirements
This commit is contained in:
Manuel Miranda 2016-11-06 16:26:15 +01:00 committed by Eli Uriegas
parent 01a013b48a
commit ce8742c605
2 changed files with 40 additions and 1 deletions

38
examples/cache_example.py Normal file
View File

@ -0,0 +1,38 @@
"""
Example of caching using aiocache package. To run it you will need a Redis
instance running in localhost:6379.
Running this example you will see that the first call lasts 3 seconds and
the rest are instant because the value is retrieved from the Redis.
If you want more info about the package check
https://github.com/argaen/aiocache
"""
import asyncio
import aiocache
from sanic import Sanic
from sanic.response import json
from sanic.log import log
from aiocache import RedisCache, cached
from aiocache.serializers import JsonSerializer
app = Sanic(__name__)
aiocache.set_defaults(cache=RedisCache)
@cached(key="my_custom_key", serializer=JsonSerializer())
async def expensive_call():
log.info("Expensive has been called")
await asyncio.sleep(3)
return {"test": True}
@app.route("/")
async def test(request):
log.info("Received GET /")
return json(await expensive_call())
app.run(host="0.0.0.0", port=8000, loop=asyncio.get_event_loop())

View File

@ -2,6 +2,7 @@ httptools
ujson ujson
uvloop uvloop
aiohttp aiohttp
aiocache
pytest pytest
coverage coverage
tox tox
@ -9,4 +10,4 @@ gunicorn
bottle bottle
kyoukai kyoukai
falcon falcon
tornado tornado