-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache.py
More file actions
76 lines (59 loc) · 1.6 KB
/
Copy pathcache.py
File metadata and controls
76 lines (59 loc) · 1.6 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import json
import os
from datetime import datetime, timedelta
from config import CACHE_FILE
CACHE_FILE = os.path.join(os.path.dirname(__file__), CACHE_FILE)
# TTLs in hours. None = cache forever (historical data never changes)
TTL = {
"driverStandings": 1,
"constructorStandings": 1,
"circuits": 24,
"drivers": 24,
"races": 24,
"results": None,
"qualifying": None,
"laps": None,
"pitstops": None,
"sprint": None,
"status": None,
}
def _load() -> dict:
if not os.path.exists(CACHE_FILE):
return {}
with open(CACHE_FILE, "r") as f:
return json.load(f)
def _save(cache: dict):
with open(CACHE_FILE, "w") as f:
json.dump(cache, f, indent=2)
def _ttl_for(endpoint: str) -> int | None:
for key, ttl in TTL.items():
if key in endpoint:
return ttl
return 1
def get(endpoint: str):
cache = _load()
entry = cache.get(endpoint)
if not entry:
return None
ttl_hours = _ttl_for(endpoint)
if ttl_hours is None:
return entry["data"]
cached_at = datetime.fromisoformat(entry["cached_at"])
if datetime.now() - cached_at < timedelta(hours=ttl_hours):
return entry["data"]
return None
def set(endpoint: str, data):
cache = _load()
cache[endpoint] = {
"data": data,
"cached_at": datetime.now().isoformat(),
}
_save(cache)
def invalidate(endpoint: str = None):
"""Clear a specific endpoint or the entire cache."""
if endpoint is None:
_save({})
else:
cache = _load()
cache.pop(endpoint, None)
_save(cache)