【发布时间】:2016-02-21 22:20:16
【问题描述】:
考虑一下这个简短的 sn-p:
import tornado
import tornado.websocket
import tornado.ioloop
import tornado.gen
import tornado.web
class NewWsHandler(tornado.websocket.WebSocketHandler):
async def on_message(self, message):
await self.write_message("echo " + message)
class OldWsHandler(tornado.websocket.WebSocketHandler):
@tornado.gen.coroutine
def on_message(self, message):
yield self.write_message("echo " + message)
app = tornado.web.Application([(r'/', OldWsHandler)])
app.listen(8080)
tornado.ioloop.IOLoop.current().start()
OldWsHandler 使用 3.5 之前的方式在 Tornado 中执行异步函数,并且运行良好。但是,as the documentation states,为了可读性和速度,最好使用PEP 0492。
文档说:
只需使用
async def foo()代替带有@gen.coroutine装饰器的函数定义,并使用await代替yield。
所以我写了NewWsHandler。但是,在发送 websocket 消息时,会引发警告:
我真的不知道如何(正确)修复它。我尝试用tornado.web.asynchronous 装饰它,但假设是HTTP verb method。所以在我覆盖finish()(不允许websockets这样做)之后,它似乎有点工作:
class NewWsHandler(tornado.websocket.WebSocketHandler):
def finish(self):
pass
@tornado.web.asynchronous
async def on_message(self, message):
await self.write_message("echo " + message)
但这看起来仍然是骇人听闻的,并且似乎与文档相矛盾。这样做的正确方法是什么?
注意:我使用的是 Python 3.5.1 和 Tornado 4.3。
【问题讨论】: