Created
July 28, 2014 02:30
-
-
Save qiuyuzhou/f04b30f12dc0e3b11f32 to your computer and use it in GitHub Desktop.
Timeout Cache decorator
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
# -*- coding: utf-8 | |
__author__ = 'Charlie Qiu <[email protected]>' | |
import time | |
class TTLCache(object): | |
_caches = {} | |
_timeouts = {} | |
def __init__(self, ttl=5): | |
self.ttl = ttl | |
@classmethod | |
def collect_garbage(cls): | |
now = time.time() | |
for func in cls._caches: | |
cache = {} | |
for key in cls._caches[func]: | |
if (now - cls._caches[func][key][1]) < cls._timeouts[func]: | |
cache[key] = cls._caches[func][key] | |
cls._caches[func] = cache | |
def __call__(self, wrapped_func): | |
self.cache = self._caches[wrapped_func] = {} | |
self._timeouts[wrapped_func] = self.ttl | |
def wrapper(*args): | |
value = self.cache.get(args) | |
if value and (time.time() - value[1]) <= self.ttl: | |
return value[0] | |
else: | |
v = wrapped_func(*args) | |
self.cache[args] = v, time.time() | |
return v | |
wrapper.func_name = wrapped_func.func_name | |
return wrapper | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment