stWDBRN/cache.py

50 lines
1.7 KiB
Python
Raw Normal View History

2024-12-05 12:53:05 +11:00
import os
import json
import hashlib
from functools import wraps
from time import time
def file_cache(folder="cache", ttl=300):
"""
Decorator to cache function results in the specified folder with a TTL.
Args:
folder (str): Directory where cached files will be stored.
ttl (int): Time-to-live for the cache in seconds.
"""
if not os.path.exists(folder):
os.makedirs(folder)
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
# Create a unique cache key based on the function name and arguments
cache_key = hashlib.md5(
f"{func.__name__}-{args}-{kwargs}".encode("utf-8")
).hexdigest()
cache_file = os.path.join(folder, f"{cache_key}.json")
# Check if cache exists and is valid
if os.path.exists(cache_file):
try:
with open(cache_file, "r") as f:
cached_data = json.load(f)
# Check if the cache has expired
if time() - cached_data["timestamp"] < ttl:
return cached_data["result"]
except (IOError, ValueError, KeyError):
pass # In case of error, re-compute the result
# Call the function and cache the result
result = func(*args, **kwargs)
try:
with open(cache_file, "w") as f:
json.dump({"timestamp": time(), "result": result}, f)
except (IOError, TypeError) as e:
print(f"Warning: Could not cache result: {e}")
return result
return wrapper
return decorator