【发布时间】:2018-03-09 18:03:37
【问题描述】:
我正在尝试使用这段代码来理解@tornado.web.asynchronous。预期的代码应该处理异步 Web 请求,但它似乎没有按预期工作。有两个端点:
1) http://localhost:5000/A (This is the time consuming request and
takes a few seconds)
2) http://localhost:5000/B (This is the fast request and takes no time to return.
但是,当我点击浏览器转到 http://localhost:5000/A 然后在运行时转到 http://localhost:5000/B 第二个请求排队并仅在 A 完成后运行。 换句话说,一个任务很耗时,但它会阻止另一个更快的任务。我做错了什么?
import tornado.web
from tornado.ioloop import IOLoop
import sys, random, signal
class TestHandler(tornado.web.RequestHandler):
"""
In below function goes your time consuming task
"""
def background_task(self):
sm = 0
for i in range(10 ** 8):
sm = sm + 1
return str(sm + random.randint(0, sm)) + "\n"
@tornado.web.asynchronous
def get(self):
""" Request that asynchronously calls background task. """
res = self.background_task()
self.write(str(res))
self.finish()
class TestHandler2(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
self.write('Response from server: ' + str(random.randint(0, 100000)) + "\n")
self.finish()
def sigterm_handler(signal, frame):
# save the state here or do whatever you want
print('SIGTERM: got kill, exiting')
sys.exit(0)
def main(argv):
signal.signal(signal.SIGTERM, sigterm_handler)
try:
if argv:
print ":argv:", argv
application = tornado.web.Application([
(r"/A", TestHandler),
(r"/B", TestHandler2),
])
application.listen(5000)
IOLoop.instance().start()
except KeyboardInterrupt:
print "Caught interrupt"
except Exception as e:
print e.message
finally:
print "App: exited"
if __name__ == '__main__':
sys.exit(main(sys.argv))
【问题讨论】:
-
您在
background_task中执行的操作是CPU 绑定操作,因此它会阻塞服务器。考虑在另一个线程中运行它。我刚才在这里回答了一个类似的问题:stackoverflow.com/questions/47442700/…
标签: python asynchronous tornado