mbishu's picture
Update backend: add new services, update dependencies, and improve configuration
44094a0
Raw History Blame Contribute Delete
1.77 kB
from __future__ import annotations
import json
import logging
from dataclasses import dataclass
from typing import Any, Optional
import redis
logger = logging.getLogger(__name__)
@dataclass
class CacheConfig:
url: str = "redis://localhost:6379/0"
prefix: str = "image_search"
default_ttl: int = 300
class CacheClient:
"""Thin wrapper around Redis for small metadata caches."""
def __init__(self, config: CacheConfig):
self.config = config
self.client: Optional[redis.Redis] = None
self._connect()
def _connect(self) -> None:
try:
self.client = redis.from_url(self.config.url, decode_responses=True)
self.client.ping()
logger.info("Connected to Redis cache at %s", self.config.url)
except Exception as exc:
logger.warning("Redis cache unavailable: %s", exc)
self.client = None
def get(self, key: str) -> Optional[Any]:
if not self.client:
return None
namespaced = f"{self.config.prefix}:{key}"
data = self.client.get(namespaced)
if data is None:
return None
try:
return json.loads(data)
except json.JSONDecodeError:
return data
def set(self, key: str, value: Any, ttl: Optional[int] = None) -> None:
if not self.client:
return
namespaced = f"{self.config.prefix}:{key}"
payload = json.dumps(value) if not isinstance(value, str) else value
self.client.set(namespaced, payload, ex=ttl or self.config.default_ttl)
def delete(self, key: str) -> None:
if not self.client:
return
namespaced = f"{self.config.prefix}:{key}"
self.client.delete(namespaced)