Python fastapi的缓存插件 fastapi-cache2

安装

> 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")

作者:spike

分类: Python

创作时间:2024-02-15

更新时间:2024-02-15

联系方式放在中括号之中例如[[email protected]],回复评论在开头加上标号例如:#1