mirror of
https://github.com/long2ice/fastapi-cache.git
synced 2026-03-25 04:57:54 +00:00
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.
31 lines
1.2 KiB
Python
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
|