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

[Question] is it possible to avoid caching when result is empty ?

Open Aassifh opened this issue 2 years ago • 3 comments

I'm trying to avoid caching when the result is empty is it possible ?

Aassifh avatar Sep 08 '22 08:09 Aassifh

You can modify the caching function, the decorator.

You could and a check for empty there, https://github.com/long2ice/fastapi-cache/blob/master/fastapi_cache/decorator.py#L80

I made a modified decorator within my project just by copy-pasting that file, and using my decorator instead of the original one. There I don't cache http redirects and such.

antont avatar Sep 09 '22 06:09 antont

i added a custom coder for my case, this way if the value is empty it will save a null value in the cache store.

according to this line and this line of decorator.py it will not accept the result from the cache store and proceeds to set a new value.

but be aware of future changes in decorator, if the logic in decorator changes you should check if this code still works.

from fastapi_cache.coder import JsonCoder, JsonEncoder
from fastapi_cache import FastAPICache
from fastapi_cache.backends.inmemory import InMemoryBackend


class APIJSONCoder(JsonCoder):
    @classmethod
    def encode(cls, value: Any):
        if not value:
            return None
        return json.dumps(value, cls=JsonEncoder)


FastAPICache.init(InMemoryBackend(), coder=APIJSONCoder)

sehraramiz avatar Sep 12 '22 06:09 sehraramiz

Can you explain more as to why you don't want an empty response cached? What is returned by the endpoint, an empty string, None, something else?

I was thinking the key builder should be able to raise an exception or return None to indicate that a request should not be cached, but that would require that you know from the arguments or the request that the response will be empty.

mjpieters avatar May 14 '23 22:05 mjpieters