【问题标题】:How to send immediate GET reponse in tornado?如何在龙卷风中立即发送 GET 响应?
【发布时间】:2016-07-04 06:23:17
【问题描述】:

我有以下代码根据 api 调用将结果发送到浏览器。

import tornado.ioloop
import tornado.web
from tornado import gen
from datetime import date



class GetGameByIdHandler(tornado.web.RequestHandler):
    @gen.coroutine
    def get(self, id):
        response = { 'id': int(id),
                     'name': 'Crazy Game',
                     'release_date': date.today().isoformat() }
        self.set_header('Content-Type', 'text/json')
        self.write(response)


        for i in range(10000000):
            for j in range(10):
                pass
        print i


application = tornado.web.Application([
    (r"/getgamebyid/([0-9]+)", GetGameByIdHandler),
], debug = True)



if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

我希望 api 在遇到self.write 时立即返回结果。 for 循环应该在那之后运行。我怎样才能完成这项工作?基本上,我不想立即返回结果。

注意:这里的循环没有真正的目的,只是因为get 函数中的这个额外的东西而延迟了结果的发送。

一个不太抽象的例子:

import tornado.ioloop
import tornado.web
from tornado import gen
from datetime import date



class GetGameByIdHandler(tornado.web.RequestHandler):
    @gen.coroutine
    def get(self, id):
        result_dict = GetResultsFromDB(id)
        response = result_dict
        self.set_header('Content-Type', 'text/json')
        self.write(response)

        # Basically i want to doSomething basedon results
        # Generated from DB
        for key in result_dict:
            if result_dict[key] == None:
                DoSomething()


application = tornado.web.Application([
    (r"/getgamebyid/([0-9]+)", GetGameByIdHandler),
], debug = True)



if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

【问题讨论】:

  • 那么for 循环是干什么用的?你能举一个不那么抽象的例子吗?
  • 循环是徒劳的。这只是一个示例,如果函数有更多结果,则只有在处理完所有结果后才会发送结果。我只是希望它立即发送结果。
  • ThreadPool.apply_async() 可能会有所帮助。
  • 你能再详细点吗?在哪里以及如何添加?
  • “你能举一个不那么抽象的例子吗?” 因为你使用的是 HTTP,所以每个请求只能发送一个响应,还有什么可做的?

标签: python api asynchronous tornado


【解决方案1】:

如果您需要在将所有数据写入套接字后运行一些代码,您可以使用tornado.web.RequestHandler.flush

    self.write(response)
    self.flush(callback=lambda: DoSomethingWrapper(response))

【讨论】:

猜你喜欢
  • 2013-09-09
  • 2015-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多