Skip to content

Commit

Permalink
Add custom key builder for cache
Browse files Browse the repository at this point in the history
  • Loading branch information
a1d4r committed Apr 4, 2024
1 parent d59bb53 commit 5d4d8c9
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
3 changes: 2 additions & 1 deletion async_api/src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,14 @@
from core.settings import settings
from db.elastic import elasticsearch
from db.redis import redis
from utils.cache import key_builder


@asynccontextmanager
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
await redis.initialize()
await elasticsearch.info()
FastAPICache.init(RedisBackend(redis), prefix="fastapi-cache")
FastAPICache.init(RedisBackend(redis), prefix="fastapi-cache", key_builder=key_builder)
yield
await redis.close()
await elasticsearch.close()
Expand Down
Empty file added async_api/src/utils/__init__.py
Empty file.
33 changes: 33 additions & 0 deletions async_api/src/utils/cache.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from typing import Any

import hashlib

from collections.abc import Callable

from starlette.requests import Request
from starlette.responses import Response


def key_builder(
func: Callable[..., Any],
namespace: str | None = "",
request: Request | None = None, # noqa: ARG001
response: Response | None = None, # noqa: ARG001
args: tuple[Any] | None = None,
kwargs: dict[str, Any] | None = None,
) -> str:
"""Key builder for fastapi-cache which does not take into account service dependencies.
See: https://github.com/long2ice/fastapi-cache/issues/279
"""
from fastapi_cache import FastAPICache

if kwargs:
kwargs = {key: value for key, value in kwargs.items() if not key.endswith("_service")}
prefix = f"{FastAPICache.get_prefix()}:{namespace}:"
return (
prefix
+ hashlib.md5( # noqa: S324
f"{func.__module__}:{func.__name__}:{args}:{kwargs}".encode(),
).hexdigest()
)

0 comments on commit 5d4d8c9

Please sign in to comment.