fastapi-caching
fastapi-caching copied to clipboard
Advanced options for cache key (headers, custom properties, ...)
First of all, thanks a lot for this project, it's basically exactly what I was looking for! :raised_hands:
However, I encountered some limitations quite soon. I'd like to have more options for configuring the keys by which objects are cached.
My use case at hand is to cache user-specific responses, so that for authenticated requests to the same route, different content is returned for different users. I see two possible solutions to this:
- Consider request headers in cache key. Some (-> make this configurable) headers could be included to the key when writing to or reading from the cache, e.g. the
Authorizationheader's contents. - Add user-defined key elements. A more generic solution is to allow the developer to specify custom values to consider as part of the cache key. Something like this:
@app.get("/products", response_model=List[Product])
async def list_products(
rcache: ResponseCache = cache_manager.from_request(),
current_user: models.User = Depends(deps.principal),
):
if rcache.exists(props={'user': current_user.id}):
return rcache.data
products = await db.fetch_products()
await rcache.set(products, tag="all-products", props={'user': current_user.id})
return products