Files
fastapi-cache/fastapi_cache/backends/redis.py
Martijn Pieters 23d439f83a Make backends store bytes instead of strings
This is, for the majority of backends, the native format anyway, and so
we save encoding and decoding when using the PickleCodec or if (in future)
a orjson Coder was to be added.

For the JsonCodec, the only thing that changed is the location where the
JSON data is encoded to bytes and decoded back again to a string.
2023-05-10 17:35:15 +01:00

31 lines
1.2 KiB
Python

from typing import Optional, Tuple, Union
from redis.asyncio.client import Redis
from redis.asyncio.cluster import RedisCluster
from fastapi_cache.backends import Backend
class RedisBackend(Backend):
def __init__(self, redis: Union[Redis[bytes], RedisCluster[bytes]]):
self.redis = redis
self.is_cluster: bool = isinstance(redis, RedisCluster)
async def get_with_ttl(self, key: str) -> Tuple[int, Optional[bytes]]:
async with self.redis.pipeline(transaction=not self.is_cluster) as pipe:
return await pipe.ttl(key).get(key).execute()
async def get(self, key: str) -> Optional[bytes]:
return await self.redis.get(key)
async def set(self, key: str, value: bytes, expire: Optional[int] = None) -> None:
return await self.redis.set(key, value, ex=expire)
async def clear(self, namespace: Optional[str] = None, key: Optional[str] = None) -> int:
if namespace:
lua = f"for i, name in ipairs(redis.call('KEYS', '{namespace}:*')) do redis.call('DEL', name); end"
return await self.redis.eval(lua, numkeys=0)
elif key:
return await self.redis.delete(key)
return 0