首先你需要一个缓存对象。 dict 是一个不错的选择。
cachetpl = {}
lastupdated = time.time()
cache = Cache()
然后创建一个类来处理你的字典中的东西:
class Cache(object):
def __init__(self):
global lastupdated
self.lastupdated = lastupdated
global cachetpl
self.cachetpl = cachetpl
def keys(self):
return self.cachetpl.keys()
def lastupdate(self):
return self.lastupdate
def meta(self, clienthash, zipcode=None):
return self.cachetpl[clienthash]
然后您需要设置一个脉冲来检查更改,也许检查 SQL 存储的 lastupdated 列。
@staticmethod
def update():
global cachetpl
global lastupdated
if not cachetpl:
return None, None
PSQL = ''' SELECT key, meta FROM schema.table WHERE lastupdated >= %s '''
changes = db.fetchall(PSQL, lastupdated)
if changes:
numchange = len(changes)
for x in changes:
cachetpl[x[0]] = x[1]
lastupdated = time.time()
return len(cachetpl), numchange
else:
lastupdated = nz.now()
return None, None
如何设置此脉冲取决于您。我使用一个名为scheduler 的python 库,并为我的应用程序使用gevent 进行异步。效果很棒。
现在你只需给你的班级打电话Cache() 并提供你想要的任何数据。我的建议是,不要返回模板,而是先将其保存在数据库中,然后再返回。让路由调用在渲染之前检查缓存版本。然后,如果数据更改,您可以修改更新以在后台呈现页面,因此下一次调用缓存是新数据。