Created
May 14, 2023 10:40
-
-
Save dolohow/1b1ffdd4c5775f75c4d2034feaf0d067 to your computer and use it in GitHub Desktop.
python cache shelve decorator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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