Description
While the FastAPICache
object is implemented as a class, it is really just a singleton namespace; all attributes are class variables and all methods are class methods. All state it holds is global.
This means you can't define multiple cache configurations, hindering component-wise application construction.
E.g. if you wanted to store your RESTful API route cache in Redis, but use an in-memory cache for the HTML-heavy frontend portion of your application, you can't right now because there is just one global backend option. Nor can you set separate prefixes, unless you set a custom namespace for each route in a group of routes, something that's easy to get wrong.
The FastAPICache
object should really be a real class. Instances could be used as the cache
decorator, as well as let you adjust configuration with lifespan events:
cache = FastAPICache(prefix="fastapi-cache")
@asynccontextmanager
async def lifespan(app: FastAPI):
redis = aioredis.from_url("redis://localhost")
cache.backend = RedisBackend(redis)
yield
app = FastAPI(lifespan=lifespan)
@app.get("/")
@cache(expire=60)
async def index():
return dict(hello="world")
The cache
object then has all the context it needs to access the backend and shared configuration but additional cache
FastAPICache
instances can be created with different settings.
For backwards compatibility the current cache
decorator could be using a global singleton instance of FastAPICache()
but issue a deprecation warning.