我有一个昂贵的功能要包含在我的 Tornado 应用程序中。功能
返回多个输出,但由于遗留原因,这些输出被访问
分别通过不同的处理程序。
有没有办法只执行一次函数,然后将结果重复使用
不同的处理程序并保留 Tornado 的异步行为?
from tornado.web import RequestHandler
from tonado.ioloop import IOLoop
# the expensive function
def add(x, y):
z = x + y
return x, y, z
# the handlers that reuse the function
class Get_X(RequestHandler):
def get(self, x, y):
x, y, z = add(x, y)
return x
class Get_Y(RequestHandler):
def get(self, x, y):
x, y, z = add(x, y)
return y
class Get_Z(RequestHandler):
def get(self, x, y):
x, y, z = add(x, y)
return z
# the web service
application = tornado.web.Application([
(r'/Get_X', Get_X),
(r'/Get_Y', Get_Y),
(r'/Get_Z', Get_Z),
])
application.listen(8888)
IOLoop.current().start()
我考虑过将函数的结果缓存在字典中,但我不确定如何让其他两个处理程序等待,而第一个处理程序创建一个字典条目。