Last active
July 5, 2018 11:51
-
-
Save jakab922/6610714 to your computer and use it in GitHub Desktop.
Caching decorator with timeout. Might not be good for class instance/class methods.
This file contains hidden or 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
from functools import wraps | |
from json import dumps | |
from datetime import datetime | |
def timeout_cache(max_timeout): | |
def timeout_cache_inner(fn): | |
fn._cache = {} | |
fn._timeout = max_timeout | |
@wraps(fn) | |
def cached(*args, **kwargs): | |
key = "%s - %s" % ( | |
dumps(args), dumps(kwargs)) | |
cache, timeout = fn._cache, fn._timeout | |
now = datetime.now() | |
if key not in cache or | |
now - cache[key]["time"] > timeout: | |
value = fn(*args, **kwargs) | |
cache[key] = { | |
"time": now, | |
"value": value | |
} | |
return cache[key]["value"] | |
return cached | |
return timeout_cache_inner |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment