【问题标题】:Why I am not able to do simultaneous requests in Tornado?为什么我不能在 Tornado 中同时请求?
【发布时间】:2018-05-24 19:57:06
【问题描述】:

龙卷风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()

【问题讨论】:

  • input 是一个阻塞函数。您需要像sys.stdin 这样的非阻塞替代方案来捕获用户输入。不久前我已经回答了一个类似的问题 - stackoverflow.com/q/49871048/1925257

标签: python python-3.x http web tornado


【解决方案1】:

只有当你这样做时它才是异步的。 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

【讨论】:

  • 谢谢@deceze 好的,我使用的是 Windows 7,有什么不同吗?
  • 据我所知没有。
  • tornadoweb.org/en/stable/gen.html ,根据这个我们可以使用协程或异步吗?
  • 如果您使用的是最新的 Python 版本(我想不到 3.5+?),您应该使用 async def foo(self): await some_async_task() 语法。这些只是同一底层事物的不同语法,async def/await 是当前标准。
猜你喜欢
  • 2015-10-12
  • 1970-01-01
  • 2012-08-25
  • 2021-10-20
  • 1970-01-01
  • 2013-10-17
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
相关资源
最近更新 更多