且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Tornado 中缓存和重用函数结果

更新时间:2023-11-17 16:00:34

Tornado Futures 是可重复使用的,因此您可以在生成它之前简单地保存 Future.许多现成的缓存装饰器(如 python 3.2 的 functools.lru_cache 就可以工作,如果你把它们放在 @gen.coroutine 的前面:

Tornado Futures are reusable, so you can simply save the Future before yielding it. Many off-the-shelf caching decorators (like python 3.2's functools.lru_cache will just work if you put them in front of @gen.coroutine:

import functools
from tornado import gen
from tornado.ioloop import IOLoop

@functools.lru_cache(maxsize=100)
@gen.coroutine
def expensive_function():
    print('starting expensive_function')
    yield gen.sleep(5)
    return 1, 2, 3

@gen.coroutine
def get_x():
    print('starting get_x')
    x, y, z = yield expensive_function()
    return x

@gen.coroutine
def get_y():
    print('starting get_y')
    x, y, z = yield expensive_function()
    return y

@gen.coroutine
def get_z():
    print('starting get_z')
    x, y, z = yield expensive_function()
    return z

@gen.coroutine
def main():
    x, y, z = yield [get_x(), get_y(), get_z()]
    print(x, y, z)

if __name__ == '__main__':
    IOLoop.current().run_sync(main)

打印:

starting get_x
starting expensive_function
starting get_y
starting get_z
finished expensive_function
1 2 3