This repository has been archived on 2023-10-01. You can view files and clone it, but cannot push or open issues or pull requests.
PyNyaaTa/pynyaata/cache/redis.py

26 lines
673 B
Python
Raw Normal View History

2022-10-26 13:06:04 +00:00
from json import dumps, loads
2023-01-04 15:57:16 +00:00
from os import getenv
2022-10-26 13:06:04 +00:00
from typing import List, Optional
2022-12-22 00:01:21 +00:00
2022-10-26 13:06:04 +00:00
from pynyaata.types import Cache, RemoteFile
2022-12-22 00:01:21 +00:00
from redis import ConnectionError, Redis
2023-01-04 15:57:16 +00:00
CACHE_TIMEOUT = int(getenv("CACHE_TIMEOUT", 60 * 60))
REDIS_URL: Optional[str] = getenv("REDIS_URL")
2022-12-22 00:01:21 +00:00
if not REDIS_URL:
raise ConnectionError(f"Invalid REDIS_URL: {REDIS_URL}")
2022-10-26 13:06:04 +00:00
client = Redis.from_url(REDIS_URL)
class RedisCache(Cache):
def get(self, key: str) -> Optional[List[RemoteFile]]:
2022-12-22 00:01:21 +00:00
data = client.get(key)
return loads(str(data)) if data else None
2022-10-26 13:06:04 +00:00
def set(self, key: str, data: List[RemoteFile]):
return client.set(key, dumps(data), CACHE_TIMEOUT)