fastapi-cache
fastapi-cache copied to clipboard
[QUESTION] Is there an ability to run a function when the cache is used or key is set?
Is it possible to run a function whenever a cache is used or cache key is set? Ideally something similar to the custom_key_coder , for example:
def key_set_function(
func,
namespace: Optional[str] = "",
request: Request = None,
response: Response = None,
*args,
**kwargs,
):
// Do something
return something
@app.get("/")
@cache(expire=60, coder=JsonCoder , key_set_handler=key_set_function)
async def index(request: Request, response: Response):
return dict(hello="world")
I'm aware of aiocache having hooks which are implemented via 'plugins' that you can run before and after a new key is set. Thanks!
I couldn't find a direct way to do it, so I've created a PR that allows custom event handlers. Example usage:
Via a decorator:
@FastAPICache.on_event("existing_key")
def exists_in_cache(func, *args, **kwargs):
print("Existing key")
return None
@FastAPICache.on_event("new_key")
def new_in_cache(func, *args, **kwargs):
print("New key set")
return None
Via a class method:
def exists_in_cache(func, *args, **kwargs):
print("Existing key")
return None
def new_in_cache(func, *args, **kwargs):
print("New key set")
return None
FastAPICache.set_on_existing_key(exists_in_cache)
FastAPICache.set_on_new_key(new_in_cache)
@long2ice - let me know if you have any feedback
@long2ice - have you had a chance to review?
I'd love to see it in action! Actually I am now checking my API performance and would like to know whether cache is used or not.
I could perhaps take a look at this. What are the use-cases here? Is it purely for producing performance metrics?