如何在龙卷风中立即发送GET响应?

时间:2016-07-04 06:23:17

标签: python api asynchronous tornado

我有以下代码根据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()

1 个答案:

答案 0 :(得分:1)

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

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