fastapi-cache icon indicating copy to clipboard operation
fastapi-cache copied to clipboard

[QUESTION] Is there an ability to run a function when the cache is used or key is set?

Open calum-mcg opened this issue 2 years ago • 4 comments

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!

calum-mcg avatar Sep 01 '21 17:09 calum-mcg

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

calum-mcg avatar Sep 03 '21 17:09 calum-mcg

@long2ice - have you had a chance to review?

calum-mcg avatar Sep 10 '21 09:09 calum-mcg

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.

rsurgiewicz avatar Sep 15 '21 08:09 rsurgiewicz

I could perhaps take a look at this. What are the use-cases here? Is it purely for producing performance metrics?

mjpieters avatar May 14 '23 22:05 mjpieters