首页 > 解决方案 > 为什么我不能在 Tornado 中同时请求?

问题描述

龙卷风APP下面有2个端点。one(/) 很慢,因为它等待 IO 操作,而 other(/hello) 很快。我的要求是同时向两个端点发出请求。我观察到它只有在完成第一个请求后才需要第二个请求。即使它是异步的,为什么它不能同时处理两个请求?如何使其同时处理?

编辑:我使用的是 Windows 7,Eclipse IDE

****************Module*****************
import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def get(self):
        self.do_something()
        self.write("FINISHED")
        self.finish()

    def do_something(self):
        inp = input("enter to continue")
        print (inp)
class HelloHandler(tornado.web.RequestHandler):

    def get(self):
        print ("say hello")
        self.write("Hello bro")
        self.finish(
def make_app():
    return tornado.web.Application([
    (r"/", MainHandler),
    (r"/hello", HelloHandler)
])
if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

标签: pythonpython-3.xhttpwebtornado

解决方案


只有当你这样做时它才是异步的。Tornado 服务器在单个线程中运行。如果该线程被同步函数调用阻塞,则在此期间该线程上不会发生任何其他事情。@tornado.web.asynchronous启用的是生成器的使用:

@tornado.web.asynchronous
def get(self):
    yield from self.do_something()
    ^^^^^^^^^^

这个yield/ yield from(在当前的 Python 版本中await)特性会暂停函数并让其他代码在同一线程上运行,同时异步调用在其他地方完成(例如等待来自数据库的数据,等待网络请求返回响应)。即,如果 Python 不需要主动做某事而是等待外部进程完成,它可以为其他任务提供处理能力。但是由于您的函数非常多地在前台运行并阻塞线程,因此不会发生其他任何事情。

请参阅http://www.tornadoweb.org/en/stable/guide/async.htmlhttps://docs.python.org/3/library/asyncio.html


推荐阅读