Skip to main content

FastAPI Simple Cache

Project description

FastAPI Simple Cache

Tests Coverage Package version Supported Python versions

FastAPI Simple Cache will cache responses from a decorated endpoint if the response is JSON encodable or a FastAPI Response.

Quick start

from fastapi import FastAPI, Request

app = FastAPI()

# Initialize in startup event
from fastapi_simple_cache import FastAPISimpleCache
from fastapi_simple_cache.backends.inmemory import InMemoryBackend
@app.on_event("startup")
async def startup():
    backend = InMemoryBackend()
    FastAPISimpleCache.init(backend=backend)
    pass

# Use the @cache decorator
from fastapi_simple_cache.decorator import cache
@app.get("/")
@cache(expire=3600)  # Set expiration in seconds
def root(request: Request):  # Add a Request typed parameter
    return {"datetime": datetime.utcnow()}

Check here for FastAPI application examples with different backends and features.

Installation

The installation depends on the backend.

  • In memory: pip install fastapi-simple-cache
  • Redis: pip install "fastapi-simple-cache[redis]"
  • Firestore: pip install "fastapi-simple-cache[firestore]"

Backends

In memory

The InMemoryBackend class implements an in-memory backend.

from fastapi_simple_cache.backends.inmemory import InMemoryBackend

@app.on_event("startup")
async def startup():
    backend = InMemoryBackend()
    FastAPISimpleCache.init(backend=backend)

Redis

The RedisBackend class implements a Redis backend.

from redis.asyncio import ConnectionPool, client
from fastapi_simple_cache.backends.redis import RedisBackend


@app.on_event("startup")
async def startup():
    pool = ConnectionPool.from_url(url="redis://localhost:6379")
    backend = RedisBackend(redis=client.Redis(connection_pool=pool))
    FastAPISimpleCache.init(backend=backend)

Firestore

The FirestoreBackend class implements a Google Firestore backend.

import firebase_admin
from firebase_admin import firestore, credentials
from fastapi_simple_cache.backends.firestore import FirestoreBackend

@app.on_event("startup")
async def startup():
    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)

Features

Namespaces

You can add the parameter namespace on cache initialization with FastAPISimpleCache.init 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")
async def startup():
    FastAPISimpleCache.init(
        backend=backend,
        namespace="my-app"
    )
    pass

Multi backends

Use more than one backend to cache responses with the backend parameter on cache initialization with FastAPISimpleCache.init. This feature is useful if you want to check an in-memory cache before an external cache.

from fastapi_simple_cache.backends.inmemory import InMemoryBackend
from fastapi_simple_cache.backends.redis import RedisBackend

inmem_backend = InMemoryBackend()
redis_backend = RedisBackend(...)

@app.on_event("startup")
async def startup():
    FastAPISimpleCache.init(
        backend=[inmem_backend, redis_backend]
    )
    pass

Valid status codes

Set valid status codes to cache responses in the @cache parameter status_codes (defaults to [200]).

@app.get("/")
@cache(expire=3600, status_codes=[200, 201])
def root(request: Request):
    return {"datetime": datetime.utcnow()}

License

FastAPI Fire Cache is released under the GNU General Public License v3.0 or later, see here for a description of this license, or see the LICENSE file for the full text.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastapi-simple-cache-0.1.2.tar.gz (23.0 kB view details)

Uploaded Source

Built Distribution

fastapi_simple_cache-0.1.2-py3-none-any.whl (20.2 kB view details)

Uploaded Python 3

File details

Details for the file fastapi-simple-cache-0.1.2.tar.gz.

File metadata

  • Download URL: fastapi-simple-cache-0.1.2.tar.gz
  • Upload date:
  • Size: 23.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: python-requests/2.28.1

File hashes

Hashes for fastapi-simple-cache-0.1.2.tar.gz
Algorithm Hash digest
SHA256 cebc2c440402ecbcdafb722ebeedba8113e74a55ba34c425e97a935e6a79ed77
MD5 4e423981bb8a28562670440236247dc5
BLAKE2b-256 06676c3aa51b1598b9ebf3d760f2e9cd4ab530ae4342f3c2cc33357cf2d6a008

See more details on using hashes here.

File details

Details for the file fastapi_simple_cache-0.1.2-py3-none-any.whl.

File metadata

File hashes

Hashes for fastapi_simple_cache-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 01a8a6c42b2a3f5aab0fe78937b7b6d505c59b717a3006ca13ba9030e8298f06
MD5 00ad111cb14feb13e1b5719988f1f60c
BLAKE2b-256 e80717e94402c944bd9aea072befa3a57fcbc6327b3e2993858146346f2bd61f

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page