Tornado 6.0.3 from 4.2: 模块“tornado.web”没有属性“asynchronous”

han*_*zgs 8 tornado

我已从 tornado 4.2 转移到 tornado 6.0.3,出现错误

AttributeError: 模块 'tornado.web' 没有属性 'asynchronous'

根据tornado v6 中的讨论,似乎已经删除了 tornado.web.asynchronous 协程。在代码中解决这个问题的任何不同方法?

我把@tornado.web.asynchronous 改成@tornado.gen.coroutine,那是固定的,接下来我得到了

运行时错误:完成()后无法写入()

根据运行时错误:在完成()之后无法写入()。可能是由于使用没有 @asynchronous 装饰器的异步操作引起的

我在 write() 之后有 self.finish(),没有错误,但没有得到任何输出

这是我的代码

class MyHandler(RequestHandler):
    _thread_pool = ThreadPoolExecutor(max_workers=10)

    @tornado.gen.coroutine
    def post(self):
        try:
            data = tornado.escape.json_decode(self.request.body)
            self.predict('mod1')
        except Exception:
            self.respond('server_error', 500)

    @concurrent.run_on_executor(executor='_thread_pool')
    def _b_run(self, mod, X):
        results = do some calculation
        return results

    @gen.coroutine
    def predict(self, mod):  
        model = mod (load from database)
        values = (load from database)
        results = yield self._b_run(model, values)
        self.respond(results)

    def respond(self, code=200):
        self.set_status(code)
        self.write(json.JSONEncoder().encode({
            "status": code
        }))
        self.finish()
Run Code Online (Sandbox Code Playgroud)

虽然完成是在写之后,但我没有得到输出

xyr*_*res 4

任何用 修饰的方法或函数都gen.coroutine应该使用yield语句来调用。否则协程将不会运行。

所以,当你调用它时,你需要yield该方法。predict

@gen.coroutine
def post(self):
    ...
    yield self.predict('mod1')
    ...
Run Code Online (Sandbox Code Playgroud)