a-luna / fastapi-redis-cache

A simple and robust caching solution for FastAPI that interprets request header values and creates proper response header values (powered by Redis)

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

@cache decorator is getting skipped

yungtilly opened this issue · comments

Hello,

I am facing an error where the @cache decorator does not seem to be producing any output or writing any keys.

I started the Redis client according to the docs:

def startup():
    redis_cache = FastApiRedisCache()
    redis_cache.init(
        host_url = os.environ.get("REDIS_URL", LOCAL_REDIS_URL),
        prefix="multitenant_cache"
    )

and applied the decorator as follows:

@cache()
def GetNewOrder(request: Request):
   ...
    return Response(status_code = resp.status_code, content = resp.content, headers = cleanupRespHeaders(resp.headers))

When I check my server output, I see where redis_cache successfully connects to my Redis server, but I'm not getting any output that indicates that it's caching, and I'm not getting any new keys in my Redis database. Any idea if I'm missing some setup step or doing something else wrong here?

FastAPI endpoints are created by decorating a function with a path operation that specifies the HTTP method that the endpoint responds to (@app.get("/new_order") in the code below).

The @cache decorator must be the first decorator applied to the GetNewOrder function, with the path operation decorator applied on top of @cache. If you decorate a function with @cache but do not apply the path operation decorator than no caching behavior will be performed.

@app.get("/new_order")
@cache()
def GetNewOrder(request: Request):
   ...
    return Response(status_code = resp.status_code, content = resp.content, headers = cleanupRespHeaders(resp.headers))

Let me know if this fixes things for you!

Thanks for the quick response! Sorry I left the @app.get(/orders/new) decorator out of my initial post, but I did have that there during my initial tests. Just for a little more context, here's the setup portion of my code:

from fastapi_redis_cache import FastApiRedisCache, cache

app = FastAPI()

LOCAL_REDIS_URL = "redis://:ubuntu@127.0.0.1:6379"

@app.on_event("startup")
def startup():
    redis_cache = FastApiRedisCache()
    redis_cache.init(
        host_url = os.environ.get("REDIS_URL", LOCAL_REDIS_URL),
        prefix="multitenant_cache",
        response_header = "x-multitenant-cache"
    )

One other thought is that I'm making at least one internal API call for each route, so there's at least one extra request and response object in each call (although I am using the requests module for these calls, not FastAPI). Could that disrupt the decorator in any way, or does the decorator only pick up the FastAPI response that my route actually returns?

This issue seems similar to my new issue: #58