Files
fastapi-cache/examples/main.py

43 lines
957 B
Python
Raw Normal View History

import aioredis
2020-08-26 18:04:57 +08:00
import uvicorn
from fastapi import FastAPI
from starlette.requests import Request
from starlette.responses import Response
from fastapi_cache import FastAPICache
2020-10-08 15:10:34 +08:00
from fastapi_cache.backends.inmemory import InMemoryBackend
from fastapi_cache.backends.redis import RedisBackend
2020-10-08 15:10:34 +08:00
from fastapi_cache.decorator import cache
2020-08-26 18:04:57 +08:00
app = FastAPI()
2020-10-08 15:10:34 +08:00
ret = 0
2020-08-26 18:04:57 +08:00
2020-10-08 15:10:34 +08:00
2020-11-03 18:08:06 +08:00
@cache(namespace="test", expire=1)
2020-10-08 15:10:34 +08:00
async def get_ret():
global ret
ret = ret + 1
return ret
2020-08-26 18:04:57 +08:00
@app.get("/")
@cache(namespace="test", expire=20)
2020-08-26 18:04:57 +08:00
async def index(request: Request, response: Response):
2020-10-08 15:10:34 +08:00
return dict(ret=await get_ret())
2020-08-26 18:04:57 +08:00
2020-11-03 18:08:06 +08:00
@app.get("/clear")
async def clear():
return await FastAPICache.clear(namespace="test")
2020-08-26 18:04:57 +08:00
@app.on_event("startup")
async def startup():
redis = aioredis.from_url(url="redis://localhost")
FastAPICache.init(RedisBackend(redis), prefix="fastapi-cache")
2020-08-26 18:04:57 +08:00
if __name__ == "__main__":
uvicorn.run("main:app", debug=True, reload=True)