使用带有生成器功能的Flask Cache

时间:2013-01-04 21:21:14

标签: python flask

我正在尝试使用Flask-Cache来缓存生成器函数。 Flask-Cache需要酸洗,因为发生器无法酸洗,这是一个问题。在Flask-Cache中使用生成器是否有任何解决方法?

1 个答案:

答案 0 :(得分:0)

如果要缓存结果,只需在生成器上调用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