Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/api/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在龙卷风中立即得到响应?_Python_Api_Asynchronous_Tornado - Fatal编程技术网

Python 如何在龙卷风中立即得到响应?

Python 如何在龙卷风中立即得到响应?,python,api,asynchronous,tornado,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),

我有以下代码根据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
时立即返回结果。此后应运行的
循环。我怎样才能做到这一点?基本上,我不想立即返回结果

注意:这里的循环没有真正的用途,只是为了证明结果的发送被延迟,因为
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()

如果在将所有数据写入套接字后需要运行某些代码,可以使用:


那么
循环的
是做什么的呢?你能举一个不那么抽象的例子吗?这个循环毫无意义。这只是一个例子,如果函数有更多内容,那么只有在处理完所有内容后才会发送结果。我只是想让它立即发送结果。
ThreadPool.apply\u async()
可能会有帮助。您能详细说明一下吗?在何处以及如何添加此内容?“您能给出一个不那么抽象的示例吗?”因为您使用HTTP,每个请求只能发送一个响应,还有什么其他操作吗?这很好。但如果
DoSomething
正在进行,那么另一个http get请求将等待上一个请求完成。怎么能避免呢?嗯,看一看和类似的话题
    self.write(response)
    self.flush(callback=lambda: DoSomethingWrapper(response))