-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.py
More file actions
53 lines (42 loc) · 1.33 KB
/
Copy pathcache.py
File metadata and controls
53 lines (42 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
"""A tiny caching helper backed by Redis, with a safe in-memory fallback.
The fallback means the app and tests run even when Redis isn't available. In
production you'd rely on Redis so the cache is shared across worker processes.
"""
import json
from typing import Any, Optional
try:
import redis # type: ignore
from app.config import settings
_client: Optional["redis.Redis"] = redis.Redis.from_url(
settings.redis_url, decode_responses=True
)
except Exception: # redis not installed or unreachable
_client = None
# In-memory fallback store.
_memory: dict[str, str] = {}
def cache_get(key: str) -> Optional[Any]:
raw: Optional[str]
if _client is not None:
try:
raw = _client.get(key)
except Exception:
raw = _memory.get(key)
else:
raw = _memory.get(key)
return json.loads(raw) if raw else None
def cache_set(key: str, value: Any, ttl_seconds: int = 60) -> None:
raw = json.dumps(value, default=str)
if _client is not None:
try:
_client.set(key, raw, ex=ttl_seconds)
return
except Exception:
pass
_memory[key] = raw
def cache_delete(key: str) -> None:
if _client is not None:
try:
_client.delete(key)
except Exception:
pass
_memory.pop(key, None)