【发布时间】:2015-11-29 04:57:02
【问题描述】:
我的 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()
我考虑过在字典中缓存函数的结果,但我不确定如何让其他两个处理程序等待,而第一个处理程序创建一个字典条目。
【问题讨论】: