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

How to invalidate the cache for a post method

Open coolsnake opened this issue 2 years ago • 7 comments

I want to invalidate the cache if user call POST method to update data into database, so that th GET method can return the latest data to user.

coolsnake avatar Sep 10 '23 13:09 coolsnake

You need to delete a key by yourself. Of course, you should use a custom key builder to get the key or delete it by using namespace.

Here's the later example. e.g.

from redis import Redis
from fastapi import FastAPI
from fastapi_cache.decorator import cache

app = FastAPI()
redis = Redis()


@app.get("/")
@cache(namespace="some_namespace")
def get_some_data():
    return {"data": "some data from database"}


@app.post("/")
def update_some_data():
    for key in redis.keys("some_namespace:*"):
        redis.delete(key)
    return {"data": "updated data"}

If the namespace is too large, use scan_iter rather than keys function.

hard-coders avatar Sep 19 '23 09:09 hard-coders

Thanks. But it looks we can not find key by redis.keys("some_namespace:*") without custom key builder because the key is finally hashed.

coolsnake avatar Oct 01 '23 13:10 coolsnake

Thanks. But it looks we can not find key by redis.keys("some_namespace:*") without custom key builder because the key is finally hashed.

You are right. That's why I told you, "You should use a custom key builder". FastAPI-Cache hash keys using MD5 default, so you cannot identify resources. In general, if you don't have to invalidate immediately, set the TTL value properly.

hard-coders avatar Oct 04 '23 02:10 hard-coders