简体   繁体   English

返回后请求处理程序中的龙卷风流程数据

[英]Tornado process data in request handler after return

In a tornado request handler if I have to call function foo() which doesn't affect what's returned to the user, it makes sense to return result to the user first and then call foo(). 在龙卷风请求处理程序中,如果我必须调用函数foo()而不影响返回给用户的内容,则首先将结果返回给用户然后调用foo()是有意义的。 Is it possible to do this easily in tornado (or with some third-party package)? 龙卷风(或使用某些第三方包装)是否可以轻松完成此操作?

It's extremely easy: 这非常简单:

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

ioloop.add_callback,Tornado将在下一次IOLoop迭代中执行回调。

bad advice warning: you can use multiprocessing. 坏建议警告:您可以使用多处理。

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

be careful that you close all of your database connections (in the spawned code) and do whatever else tornado might do when it normally completes a request without a subprocess. 请小心关闭所有数据库连接(在生成的代码中)并执行龙卷风在正常完成没有子进程的请求时可能执行的任何操作。 The other answers sound better. 其他答案听起来更好。 But, you can do this. 但是,你可以做到这一点。 Don't do this. 不要这样做。

No it's not "easy" out-of-the-box. 不,它不是“简单”的开箱即用。 What you're referring to is "fire and forget". 你所指的是“火与忘记”。 Even if you use a thread pool to farm out the request, that thread pool will belong to the main python process that belongs to Tornado. 即使您使用线程池来扩展请求,该线程池也将属于属于Tornado的主python进程。

The best approach is a message queue. 最好的方法是消息队列。 Something like Carrot. 像胡萝卜一样的东西。 That way, suppose you have a page where users can execute to start generating a HUGE report, you can start it in a message queue and then finish the Tornado request and with some AJAX magic and other tricks (outside the scope of Tornado) you can sit back and wait till the message queue has finished it's job (which could technically be happening on a distributed server in a different physical location). 这样,假设您有一个页面,用户可以执行该页面以开始生成巨大的报告,您可以在消息队列中启动它,然后完成Tornado请求,并使用一些AJAX魔术和其他技巧(在Tornado的范围之外),您可以坐下来等待消息队列完成它的工作(技术上可能发生在不同物理位置的分布式服务器上)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM