I have an expensive function to include in my Tornado app. The function returns several outputs but, for legacy reason, these outputs are accessed separately through different handlers.
Is there a way to execute the function only once, re-use the result for the different handlers and preserve Tornado's asynchronous behavior?
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()
I thought about about caching the result of the function in a dictionary, but I'm not sure on how to make the two other handlers wait, while the first one creates a dictionary entry.