Tornado process data in request handler after return

In the tornado request handler, if I need to call the function foo (), which does not affect what is returned to the user, it makes sense to first return the result to the user, and then call foo (). Can this be done easily in a tornado (or using a third-party package)?

+8
python tornado
source share
4 answers

No, this is not "easy" out of the box. What you are talking about is "fire and forget." Even if you use a thread pool to process the request, this thread pool will belong to the main python process owned by Tornado.

The best approach is a message queue. Something like Carrots. Thus, suppose you have a page on which users can start creating a HUGE report, you can run it in the message queue, and then complete the Tornado request and with some AJAX magicians and other tricks (outside of Tornado) you can respond and wait until the message queue completes this task (which might happen technically on a distributed server in another physical location).

-one
source share

It is very simple:

class Handler(tornado.web.RequestHandler): def get(self): self.write('response') self.finish() # Connection is now closed foo() 
+9
source share

ioloop.add_callback, Tornado will call back at the next iteration of IOLoop.

+5
source share

warning of bad tips: you can use multiprocessing.

http://docs.python.org/library/multiprocessing.html

be careful to close all database connections (in the generated code) and do everything that a tornado could do when it usually completes a request without a subprocess. Other answers sound better. But you can do it. Do not do this.

0
source share

All Articles