API Headers giving me MISS even though response is cached #448
Closed
ShantanuKudva
started this conversation in
General
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Below is a piece of code that configures the cache (I am using python 3.8)
`from typing_extensions import AsyncIterator
from contextlib import asynccontextmanager
from fastapi import FastAPI
from starlette.requests import Request
from starlette.responses import Response
from fastapi_cache import FastAPICache
from fastapi_cache.backends.redis import RedisBackend
from fastapi_cache.decorator import cache
from redis import asyncio as aioredis
async def init_cache():
try:
redis = aioredis.from_url( # type: ignore
os.environ.get('REDIS_URL', 'redis://localhost'),
encoding='utf-8',
decode_responses=False,
)
FastAPICache.init(RedisBackend(redis), prefix='igw-cache')
print('Cache initialized successfully.')
except Exception as e:
print(f'Error initializing cache: {e}')
finally:
await redis.close()
print('Redis connection closed.')
@asynccontextmanager
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
await init_cache()
yield
app = FastAPI(root_path=os.environ.get("ROOT_PATH", ''), lifespan=lifespan)
app.include_router(r1.router)
app.include_router(r2.router)
app.include_router(r3.router)
app.include_router(r4.router)
app.include_router(r5.router)`
and below is the code in one of the routers
@router.get("/dashboard/topLocations") @cache(expire=60) def get_top_locations( count: Annotated[int, Query(ge=1, le=10)], fromTime:datetime.datetime = Query( default=(datetime.datetime.now(tz=datetime.timezone.utc)- datetime.timedelta(days=7)).replace(hour=0, minute=0, second=0, microsecond=0), description="End time of the range" ), toTime: datetime.datetime = Query( default=datetime.datetime.now(tz=datetime.timezone.utc).replace(hour=23, minute=59, second=59, microsecond=999999), description="Start time of the range" )) -> TopLocations:
The response is being cached, but in my headers i am getting a MISS rather than a hit.
I tried to change the cache contents to have a TTL of -1, which gave me a HIT.
Is this a predictible behaviour?
Beta Was this translation helpful? Give feedback.
All reactions