Skip to content

Instantly share code, notes, and snippets.

@vimiix
Created May 29, 2018 07:21
Show Gist options
  • Save vimiix/b8ff66821c7314e047315a03ad34b1dc to your computer and use it in GitHub Desktop.
Save vimiix/b8ff66821c7314e047315a03ad34b1dc to your computer and use it in GitHub Desktop.
使用全局变量做数据缓存
#coding: utf8
import hashlib
import pickle
import time
CACHE = {}
def is_obsolete(entry, duration):
return time.time() - entry['time'] > duration
def compute_key(func, args, kw):
key = pickle.dumps((func.__name__, args, kw))
return hashlib.sha1(key).hexdigest()
def cache(duration=10):
def _cache(func):
def __cache(*args, **kw):
key = compute_key(func, args, kw)
if key in CACHE and not is_obsolete(CACHE[key], duration) and kw.get(""):
return CACHE[key]['value']
result = func(*args, **kw)
CACHE[key] = {'value': result, 'time': time.time()}
return result
return __cache
return _cache
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment