安装
> pip install fastapi-cache2
or
> pip install "fastapi-cache2[redis]"
or
> pip install "fastapi-cache2[memcache]"
or
> pip install "fastapi-cache2[dynamodb]"
使用例子
@app.get("/")
@cache(expire=60)
async def index():
return dict(hello="world")
@app.on_event("startup")
async def startup():
redis = aioredis.from_url("redis://localhost", encoding="utf8", decode_responses=True)
FastAPICache.init(RedisBackend(redis), prefix="fastapi-cache")
自定义缓存key生成器
def my_key_builder(
func,
namespace: Optional[str] = "",
request: Request = None,
response: Response = None,
*args,
**kwargs,
):
prefix = FastAPICache.get_prefix()
cache_key = f"{prefix}:{namespace}:{func.__module__}:{func.__name__}:{args}:{kwargs}"
return cache_key
@app.get("/")
@cache(expire=60, coder=JsonCoder, key_builder=my_key_builder)
async def index():
return dict(hello="world")