Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tornado 6.0.3 from 4.2: module 'tornado.web' has no attribute 'asynchronous'

Tags:

tornado

I have moved from tornado 4.2 to tornado 6.0.3, I got the error

AttributeError: module 'tornado.web' has no attribute 'asynchronous'

as per discussion in tornado v6 seems to have dropped tornado.web.asynchronous coroutine. any different way of fixing this in code?

I changed @tornado.web.asynchronous as @tornado.gen.coroutine, that is fixed, next I got

RuntimeError: Cannot write() after finish()

as per RuntimeError: Cannot write() after finish(). May be caused by using async operations without the @asynchronous decorator

I have the self.finish() after the write(), no errors, but not getting any output

here is my code

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()

though the finish is after write, I am not getting output

like image 288
hanzgs Avatar asked Jul 10 '19 06:07

hanzgs


1 Answers

Any method or function decorated with gen.coroutine should be called using a yield statement. Otherwise the coroutine won't run.

So, you need to yield the predict method when you're calling it.

@gen.coroutine
def post(self):
    ...
    yield self.predict('mod1')
    ...
like image 165
xyres Avatar answered Oct 02 '22 18:10

xyres