FastAPI Session Cache
from fastapi.security import HTTPBasicCredentials
from fastapi.security.http.basic import HTTPBasic
from fastapi_cache import FastAPICache
from fastapi_cache.backends.memory import MemoryBackend
from starlette.responses import JSONResponse
backend = MemoryBackend()
cache = FastAPICache(backend)
app = FastAPI()
security = HTTPBasic()
@app.get("/cached")
async def cached_route(credentials: HTTPBasicCredentials = security):
username = credentials.username
cached_data = await cache.get(username)
if not cached_data:
# Fetch data from database or external source
data = ...
await cache.set(username, data)
return JSONResponse(content={"data": cached_data})