-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcache_manager.py
More file actions
53 lines (44 loc) · 1.75 KB
/
cache_manager.py
File metadata and controls
53 lines (44 loc) · 1.75 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
import json
import os
from datetime import datetime, timedelta
import logging
logger = logging.getLogger(__name__)
CACHE_FILE = 'data_cache.json'
TICKER_CACHE_FILE = 'ticker_cache.json'
# Cache durations for different types
CACHE_DURATIONS = {
'data': timedelta(days=1),
'ticker': timedelta(days=9999) # don't expire
}
def load_cache(cache_type='data'):
"""Load data from cache if it exists and is not expired."""
cache_file = TICKER_CACHE_FILE if cache_type == 'ticker' else CACHE_FILE
cache_duration = CACHE_DURATIONS.get(cache_type, timedelta(days=1)) # default to 1 day if type not found
if not os.path.exists(cache_file):
return None
try:
with open(cache_file, 'r') as f:
cache = json.load(f)
# Check if cache is expired
cached_time = datetime.fromisoformat(cache['timestamp'])
if datetime.now() - cached_time > cache_duration:
logger.info(f"{cache_type} cache has expired (duration: {cache_duration})")
return None
logger.info(f"Using cached {cache_type} data")
return cache['data']
except Exception as e:
logger.error(f"Error loading {cache_type} cache: {str(e)}")
return None
def save_cache(data, cache_type='data'):
"""Save data to cache with current timestamp."""
try:
cache_file = TICKER_CACHE_FILE if cache_type == 'ticker' else CACHE_FILE
cache = {
'timestamp': datetime.now().isoformat(),
'data': data
}
with open(cache_file, 'w') as f:
json.dump(cache, f)
logger.info(f"{cache_type} data cached successfully")
except Exception as e:
logger.error(f"Error saving {cache_type} cache: {str(e)}")