Last active
August 29, 2015 14:27
-
-
Save hirokazumiyaji/d8385a9f6149cae80960 to your computer and use it in GitHub Desktop.
Cache
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 | |
from datetime import datetime | |
import threading | |
__all__ = ['get', 'clear'] | |
class Cache(dict): | |
def __getattr__(self, name): | |
if name in self: | |
return self[name] | |
return super(Cache, self).__getattr__(name) | |
_Expire = 15 * 60 | |
_Lock = threading.Lock() | |
_Cache = {} | |
def get(name, func, *args, **kwargs): | |
global _Cache | |
if _is_enable(name): | |
return _Cache[name].data | |
return _set_and_get(name, func, *args, **kwargs) | |
def clear(name=None): | |
global _Cache | |
global _Lock | |
with _Lock: | |
if name is None: | |
_Cache = {} | |
else: | |
try: | |
del _Cache[name] | |
except: | |
pass | |
def _is_enable(name): | |
global _Cache | |
global _Expire | |
now = datetime.now() | |
c = _Cache.get(name) | |
if c is None: | |
return False | |
if c.latest_datetime is None: | |
return False | |
if c.data is None: | |
return False | |
if c.latest_datetime.hour != now.hour: | |
return False | |
if (now - c.latest_datetime).seconds >= _Expire: | |
return False | |
return True | |
def _set_and_get(name, func, *args, **kwargs): | |
global _Cache | |
global _Lock | |
with _Lock: | |
result = func(*args, **kwargs) | |
_Cache[name] = Cache(latest_datetime=datetime.now(), data=result) | |
return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment