feat(backend): service cache Redis pour identifications
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
34
backend/app/services/redis_cache.py
Normal file
34
backend/app/services/redis_cache.py
Normal file
@@ -0,0 +1,34 @@
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from typing import Optional
|
||||
|
||||
_client = None
|
||||
|
||||
|
||||
def _get_client():
|
||||
global _client
|
||||
if _client is None:
|
||||
import redis
|
||||
url = os.environ.get("REDIS_URL", "redis://localhost:6379")
|
||||
_client = redis.from_url(url, decode_responses=True)
|
||||
return _client
|
||||
|
||||
|
||||
def cache_key(image_bytes: bytes) -> str:
|
||||
return f"identify:{hashlib.sha256(image_bytes).hexdigest()}"
|
||||
|
||||
|
||||
def get(image_bytes: bytes) -> Optional[list]:
|
||||
try:
|
||||
value = _get_client().get(cache_key(image_bytes))
|
||||
return json.loads(value) if value else None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def set(image_bytes: bytes, results: list, ttl: int = 604800) -> None:
|
||||
try:
|
||||
_get_client().setex(cache_key(image_bytes), ttl, json.dumps(results))
|
||||
except Exception:
|
||||
pass # cache indisponible → silencieux
|
||||
Reference in New Issue
Block a user