【发布时间】: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