[英]Why asynchronous function in tornado is blocking?
為什么在另一個請求處於“等待”狀態時未處理傳入請求?
如果你看下面的代碼,函數“get”有一個龍卷風任務,用“yield”關鍵字執行,這意味着“等待回調被執行”。 在我的代碼中,回調永遠不會執行。 如果您第二次運行請求,則在第一次處於保持狀態時,不會處理第二個請求。 如果您運行任何其他請求,它們正在處理得很好。
所以,我的行動:1。啟動應用程序2. GET localhost:8080 / - 應用程序打印輸出“來電”3. GET localhost:8080 / anotherrequest - 應用程序打印輸出“另一個請求”4. GET localhost:8080 / - 應用程序不打印任何輸出,而我期望它打印“來電”。 為什么?
那么,為什么這段代碼會被阻塞? 附上代碼示例。
我使用龍卷風2.1和python 2.7來運行此示例。
謝謝
import tornado
import tornado.web
from tornado import gen
class AnotherHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
print 'another request'
self.finish()
class MainHandler(tornado.web.RequestHandler):
def printStuff(*args, **kwargs):
print 'incoming call'
@tornado.web.asynchronous
@tornado.gen.engine
def get(self):
result = yield tornado.gen.Task(self.printStuff);
application = tornado.web.Application([
(r"/", MainHandler),
(r"/anotherrequest", AnotherHandler)
])
if __name__ == "__main__":
application.listen(8080)
tornado.ioloop.IOLoop.instance().start()
事實上,對“localhost:8080 /”的每個新請求都會導致您的應用程序打印“來電”。 但是,對“localhost:8080 /”的請求永遠不會完成 。 為了使用yield
語句, printStuff
必須接受回調並執行它。 另外,異步get
函數必須調用self.finish
:
class MainHandler(tornado.web.RequestHandler):
def printStuff(self, callback):
print 'incoming call'
callback()
@tornado.web.asynchronous
@tornado.gen.engine
def get(self):
result = yield tornado.gen.Task(self.printStuff)
self.finish()
使用Tornado的現代“coroutine”界面而不是gen.Task和gen.engine更容易:
class MainHandler(tornado.web.RequestHandler):
@gen.coroutine
def printStuff(self):
print 'incoming call'
@gen.coroutine
def get(self):
result = yield self.printStuff()
self.finish()
發現問題,它實際上是在從瀏覽器發出請求時發生的。 隨着“卷曲”,一切都按預期工作。 對造成的不便表示歉意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.