Package: fastapi-simple-cache
FastAPI Simple CacheFastAPI Simple Cache will cache responses from a decorated endpoint if the response
isJSON encodableor
aFastAPIResponse.Quick startInstallationBackendsIn memoryRedisFirestoreFeaturesNamespacesMulti backendsValid status codesNo cacheLicenseQuick startfromfastapiimportFastAPI,Requestapp=FastAPI()# Initialize in startup eventfromfastapi_simple_cacheimportFastAPISimpleCachefromfastapi_simple_cache.backends.inmemoryimportInMemoryBackend@app.on_event("startup")asyncdefstartup():backend=InMemoryBackend()FastAPISimpleCache.init(backend=backend)# Use the @cache decoratorfromfastapi_simple_cache.decoratorimportcache@app.get("/")@cache(expire=3600)# Set expiration in secondsdefroot(request:Request):# Add a Request typed parameterreturn{"datetime":datetime.utcnow()}Checkherefor FastAPI application examples with
differentbackendsandfeatures.InstallationThe installation depends on the backend.In memory:pip install fastapi-simple-cacheRedis:pip install "fastapi-simple-cache[redis]"Firestore:pip install "fastapi-simple-cache[firestore]"BackendsIn memoryTheInMemoryBackendclass implements an in-memory backend.fromfastapi_simple_cache.backends.inmemoryimportInMemoryBackend@app.on_event("startup")asyncdefstartup():backend=InMemoryBackend()FastAPISimpleCache.init(backend=backend)RedisTheRedisBackendclass implements a Redis backend.fromredis.asyncioimportConnectionPool,clientfromfastapi_simple_cache.backends.redisimportRedisBackend@app.on_event("startup")asyncdefstartup():pool=ConnectionPool.from_url(url="redis://localhost:6379")backend=RedisBackend(redis=client.Redis(connection_pool=pool))FastAPISimpleCache.init(backend=backend)FirestoreTheFirestoreBackendclass implements a Google Firestore backend.importfirebase_adminfromfirebase_adminimportfirestore,credentialsfromfastapi_simple_cache.backends.firestoreimportFirestoreBackend@app.on_event("startup")asyncdefstartup():cred=credentials.ApplicationDefault()firebase_admin.initialize_app(cred,{"projectId":"gcp_project"})db=firestore.client()collection=db.collection("cache_collection")backend=FirestoreBackend(collection=collection)FastAPISimpleCache.init(backend=backend)FeaturesNamespacesYou can add the parameternamespaceon cache initialization to modify
the storage keys. Use this feature if you need to share same cache
environment with other applications but with different keys.@app.on_event("startup")asyncdefstartup():backend=InMemoryBackend()FastAPISimpleCache.init(backend=backend,namespace="my-app")Multi backendsUse more than one backend to cache responses with thebackendparameter
on cache initialization. This feature is useful if you want to check an
in-memory cache before an external cache.fromfastapi_simple_cache.backends.inmemoryimportInMemoryBackendfromfastapi_simple_cache.backends.redisimportRedisBackend@app.on_event("startup")asyncdefstartup():inmem_backend=InMemoryBackend()redis_backend=RedisBackend(...)FastAPISimpleCache.init(backend=[inmem_backend,redis_backend])Valid status codesSet valid status codes to cache responses in the@cacheparameterstatus_codes(defaults to[200]).@app.get("/")@cache(expire=3600,status_codes=[200,201])defroot(request:Request):return{"datetime":datetime.utcnow()}No cacheAvoid storing a request/response by adding the headercache-control: no-cacheto the request. This works both for the client
and the server.LicenseFastAPI Fire Cache is released under the GNU General Public License v3.0 or
later, seeherefor a
description of this license, or see theLICENSEfile for
the full text.