Skip to content

Instantly share code, notes, and snippets.

@dolohow
Created May 14, 2023 10:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dolohow/1b1ffdd4c5775f75c4d2034feaf0d067 to your computer and use it in GitHub Desktop.
Save dolohow/1b1ffdd4c5775f75c4d2034feaf0d067 to your computer and use it in GitHub Desktop.
python cache shelve decorator
import shelve
import time
def cache(func):
def wrapper(*args, **kwargs):
with shelve.open('cache.db') as cache_db:
cache_key = f"{func.__name__}{args}{kwargs}"
if cache_key in cache_db:
# Check if data is expired
cache_time, cache_data = cache_db[cache_key]
if time.time() - cache_time < 24 * 3600:
print(f"{func.__name__} - cache hit")
return cache_data
print(f"{func.__name__} - cache miss")
result = func(*args, **kwargs)
cache_db[cache_key] = (time.time(), result)
return result
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment