-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache_manager.py
More file actions
143 lines (109 loc) · 4.13 KB
/
Copy pathcache_manager.py
File metadata and controls
143 lines (109 loc) · 4.13 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
"""Cache management for API responses and processed data."""
import json
import time
from pathlib import Path
from typing import Any, Dict, Optional
from config import CACHE_DIR, CACHE_EXPIRY
class CacheManager:
"""Manages caching of API responses and processed data."""
def __init__(self):
"""Initialize cache manager and ensure cache directory exists."""
self.cache_dir = CACHE_DIR
self.cache_dir.mkdir(parents=True, exist_ok=True)
def _get_cache_path(self, key: str) -> Path:
"""Get the file path for a cache key."""
# Use hash of key to avoid filesystem issues with long/invalid characters
safe_key = str(hash(key))
return self.cache_dir / f"{safe_key}.json"
def get(self, key: str) -> Optional[Dict[str, Any]]:
"""
Retrieve data from cache if it exists and hasn't expired.
Args:
key: Unique identifier for the cached data
Returns:
Cached data if valid, None otherwise
"""
cache_path = self._get_cache_path(key)
if not cache_path.exists():
return None
try:
with cache_path.open('r') as f:
cached = json.load(f)
# Check if cache has expired
if time.time() - cached['timestamp'] > CACHE_EXPIRY:
cache_path.unlink() # Remove expired cache
return None
return cached['data']
except (json.JSONDecodeError, KeyError, OSError) as e:
print(f"Cache read error for {key}: {str(e)}")
return None
def set(self, key: str, data: Dict[str, Any]) -> bool:
"""
Store data in cache with timestamp.
Args:
key: Unique identifier for the data
data: Data to cache
Returns:
True if successful, False otherwise
"""
cache_path = self._get_cache_path(key)
try:
cache_data = {
'timestamp': time.time(),
'data': data
}
with cache_path.open('w') as f:
json.dump(cache_data, f)
return True
except (OSError, TypeError) as e:
print(f"Cache write error for {key}: {str(e)}")
return False
def invalidate(self, key: str) -> bool:
"""
Remove item from cache.
Args:
key: Cache key to invalidate
Returns:
True if successful or file didn't exist, False on error
"""
cache_path = self._get_cache_path(key)
try:
if cache_path.exists():
cache_path.unlink()
return True
except OSError as e:
print(f"Cache invalidation error for {key}: {str(e)}")
return False
def clear(self) -> bool:
"""
Clear all cached data.
Returns:
True if successful, False on error
"""
try:
for cache_file in self.cache_dir.glob("*.json"):
cache_file.unlink()
return True
except OSError as e:
print(f"Cache clear error: {str(e)}")
return False
def get_cache_size(self) -> int:
"""
Get total size of cached data in bytes.
Returns:
Total size of cache in bytes
"""
return sum(f.stat().st_size for f in self.cache_dir.glob("*.json"))
def get_cache_stats(self) -> Dict[str, Any]:
"""
Get cache statistics.
Returns:
Dictionary containing cache statistics
"""
cache_files = list(self.cache_dir.glob("*.json"))
return {
'total_entries': len(cache_files),
'total_size_bytes': self.get_cache_size(),
'oldest_entry': min((f.stat().st_mtime for f in cache_files), default=0),
'newest_entry': max((f.stat().st_mtime for f in cache_files), default=0)
}