在构建现代化的Python应用时,性能是一个至关重要的因素。为了加速数据访问和提高应用的响应速度,缓存是一个不可或缺的利器。FastAPI-Cache2是一个强大的缓存库,它提供了简单而高效的缓存解决方案,使得在FastAPI应用中轻松集成缓存成为可能。我们很容易被这个名字给误导,它不光可以和FastAPI集成使用,任何项目都可以使用。你也可以像其他缓存工具一样使用cache作为装饰器来缓存常见的函数结果。
FastAPI-Cache2的优点
- 无依赖的轻量级设计: FastAPI-Cache2是一个轻量级的缓存库,不依赖于其他复杂的库或服务。这使得它非常易于集成到你的项目中,而且不会引入额外的复杂性。
- 基于FastAPI的原生支持: 由于FastAPI-Cache2是专门为FastAPI设计的,它充分利用了FastAPI框架的特性。这种紧密的集成使得在FastAPI应用中添加缓存变得异常简单,并且性能表现卓越。
- 支持多种后端存储: FastAPI-Cache2支持多种后端存储,包括内存、Redis等。这意味着你可以根据你的项目需求选择最合适的存储后端,从而灵活地应对不同的应用场景。
- 自定义过期策略: 该库允许你灵活地定义缓存的过期策略,以确保缓存数据的及时更新。这是一个关键的功能,尤其是在处理动态数据时,可以防止应用展示过期或不准确的信息。
- 简单易用的API: FastAPI-Cache2提供了简单而直观的API,使得缓存的设置和获取变得非常容易。这使得开发者可以专注于业务逻辑,而不必过多关心底层的缓存实现细节。
安装
> pip install fastapi-cache2
or
> pip install "fastapi-cache2[redis]"
or
> pip install "fastapi-cache2[memcache]"
or
> pip install "fastapi-cache2[dynamodb]"
案例
from fastapi import FastAPI
from starlette.requests import Request
from starlette.responses import Response
from fastapi_cache import FastAPICache
from fastapi_cache.backends.redis import RedisBackend
from fastapi_cache.decorator import cache
from redis import asyncio as aioredis
app = FastAPI()
@cache(namespace="user", expire=60)
def test():
return dict(hello="world")
@app.get("/")
@cache(expire=60)
async def index():
return dict(hello="world")
@app.get("/user")
async def user():
if random.random() > 0.5:
# 主动清除缓存
await FastAPICache.clear(namespace='user')
result = test()
return result
@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")
使用缓存装饰器
如果你想透明地缓存fastapi响应,你可以使用缓存作为路由器装饰器和视图函数之间的装饰器,并且必须将请求作为视图函数的参数传递。你也可以像其他缓存工具一样使用cache作为装饰器来缓存常见的函数结果。
参数 | 类型 | 描述 |
---|---|---|
expire | int | 表示缓存时间,单位为秒 |
namespace | str | 用于存储某些缓存项的命名空间 |
coder | 使用哪个编码器,例如JsonCoder | |
key_builder | 使用哪个键构建器,默认为内置 |
自定义编码
默认使用JsonCoder,你可以编写自定义编码器来编码和解码缓存结果,只需要继承fastapi_cache.coder.Coder。
@app.get("/")
@cache(expire=60, coder=JsonCoder)
async def index():
return dict(hello="world")
自定义键生成器
默认使用内置的key builder,如果你需要,你可以覆盖它并传入cache或FastAPICache。Init全局生效。
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")
FastAPI-Cache2作为一个高效、轻量级的缓存库,为FastAPI应用提供了强大的缓存支持。通过与其他同类库的对比,我们可以更好地了解它的优势和适用场景。在选择缓存库时,务必根据项目需求和框架选择合适的工具,以便充分发挥其优势,提升应用性能。
查看原文:高效Python缓存库FastAPI-Cache2
关注公众号 "字节航海家" 及时获取最新内容