只需创建一个缓存(python dict)来存储第一个查询并每次返回它,每N分钟清除一次缓存,为此您可以创建一个装饰器或缓存类,例如
import time
cache = {}
lastTime = time.time()
def timedCacheDecorator(func):
def wrap(*args, **kwargs):
key = str(args)+str(kwargs)
# cache for 5 seconds
global lastTime
if key not in cache or time.time() - lastTime > 5:
lastTime = time.time()
cache[key] = func(*args, **kwargs)
return cache[key]
return wrap
# lets test it
@timedCacheDecorator
def myquery():
return time.time()
print myquery()
time.sleep(1)
print myquery()
time.sleep(5)
print myquery()
time.sleep(1)
print myquery()
Run Code Online (Sandbox Code Playgroud)
输出:
1270441034.58
1270441034.58
1270441040.58
1270441040.58
Run Code Online (Sandbox Code Playgroud)
现在这个装饰器可以用在任何其结果要被缓存到某个时间或可能到一个事件的函数上,我会让这个装饰器成为一个类,这样在缓存刷新之前需要等待多少秒,而且你可以看到如何最好地生成密钥。
归档时间: |
|
查看次数: |
2936 次 |
最近记录: |