python - 为什么我不能在 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()
解决方案
只有当你这样做时它才是异步的。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.html和https://docs.python.org/3/library/asyncio.html。
推荐阅读
- javascript - 在 Javascript 中扩展的模板
- numpy - Numpy 无法使用某些名称保存
- sql - PostgreSQL:对多个值使用 ANY
- c# - 了解“SqlParameter 已被另一个 SqlParameterCollection 包含”
- visual-studio-code - 在 VS Code 中使用快捷键 Ctr+i 选择行时,光标会跳转到下面的行。如何避免?
- android - Volley服务后Android更新AppWidget
- sql - 根据在同一行的另一列中设置的值更新列
- javascript - 在javascript中,您不仅限于官方列表中的属性,为什么以及此功能称为什么
- javascript - 如何覆盖电子邮件输入验证器消息?
- html - 拉伸 SVG 以适应其父级的 100% 高度和宽度