0
我正在嘗試使用Flask-Cache來緩存發電機功能。燒瓶緩存需要酸洗,並且由於發生器不能被酸洗,這是一個問題。是否有任何解決方案使用Flask-Cache生成器?使用Flask Cache與發電機功能
我正在嘗試使用Flask-Cache來緩存發電機功能。燒瓶緩存需要酸洗,並且由於發生器不能被酸洗,這是一個問題。是否有任何解決方案使用Flask-Cache生成器?使用Flask Cache與發電機功能
如果您想緩存結果只需在生成器上調用list
,然後存儲即可。如果結果太大而無法安全地存儲在內存中(即使是暫時的),然後將結果包含在類實例中,該實例可以:restore itself when unpickled:
# Warning: This is terribly tightly bound together
# There are better ways to do this - this is just by way of example
def some_generator(identifier):
"""This could be anything
* A database wrapper
* A permutation generator
* Something that streams (and transforms) data from disk
* The possibilities are endless"""
if identifier == "result_set_1":
results = [(x, y) for x in range(10) for y in range(x)]
elif identifier == "result_set_2":
results = [(x, 0) for x in range(20)]
else:
results = [(1, 2), (3, 4)]
for row in results:
yield row
class GeneratorWrapper(object):
"""
Use::
@cache
some_function(identifier):
return GeneratorWrapper(identifier)
"""
def __init__(self, identifier=None):
self.identifier = identifier
if identifier is not None:
self.data = some_generator(identifier)
def __getstate__(self):
"""When pickled return the key to rebuilding the generator"""
return self.identifier
def __setstate__(self, state):
"""When unpickled, restore the generator using the pickled key"""
self.identifier = state
if state is not None:
self.data = some_generator(state)
def __iter__(self):
return self.data