Cache for FastAPI
Project description
fastapi-cache
Introduction
fastapi-cache
is a tool to cache fastapi response and function result, with backends support redis
and memcache
.
Features
- Support
redis
andmemcache
andin-memory
backends. - Easily integration with
fastapi
. - Support http cache like
ETag
andCache-Control
.
Requirements
asyncio
environment.redis
if useRedisBackend
.memcache
if useMemcacheBackend
.
Install
> pip install fastapi-cache2
or
> pip install fastapi-cache2[redis]
or
> pip install fastapi-cache2[memcache]
Usage
Quick Start
import aioredis
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
app = FastAPI()
@cache()
async def get_cache():
return 1
@app.get("/")
@cache(expire=60)
async def index(request: Request, response: Response):
return dict(hello="world")
@app.on_event("startup")
async def startup():
redis = await aioredis.create_redis_pool("redis://localhost", encoding="utf8")
FastAPICache.init(RedisBackend(redis), prefix="fastapi-cache")
Use cache
decorator
If you want cache fastapi
response transparently, you can use cache
as decorator between router decorator and view function and must pass request
as param of view function.
And if you want use ETag
and Cache-Control
features, you must pass response
param also.
You can also use cache
as decorator like other cache tools to cache common function result.
Custom coder
By default use JsonCoder
, you can write custom coder to encode and decode cache result, just need inherit fastapi_cache.coder.Coder
.
@app.get("/")
@cache(expire=60,coder=JsonCoder)
async def index(request: Request, response: Response):
return dict(hello="world")
Custom key builder
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(request: Request, response: Response):
return dict(hello="world")
InMemoryBackend
InMemoryBackend
only support in single node instead of distributed environment.
License
This project is licensed under the Apache-2.0 License.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for fastapi_cache2-0.1.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 8752d7f84d79156c9ceb75fa00ff23dd1c2c8bbefebb1450fbd550870116e3c4 |
|
MD5 | db5d373770ccf0f31d05be47e8a17f2c |
|
BLAKE2b-256 | e44f6815ee2c8502ec385c0f1808d174c3b8e8447f938ca773387a3fba34552f |