Search code examples
pythonpython-3.xtornado

Python3 tornado not yielding correctly?


When running the code I get an error of

ERROR:tornado.application:Future exception was never retrieved: Traceback (most recent call last): File "C:\Users\Ben\AppData\Local\Programs\Python\Python36\lib\site-packages\tornado\gen.py", line 1069, in run yielded = self.gen.send(value) File "C:\Users\Ben\Documents\GitHub\app-development\server\server.py", line 20, in serve self.write(r) File "C:\Users\Ben\AppData\Local\Programs\Python\Python36\lib\site-packages\tornado\web.py", line 708, in write raise RuntimeError("Cannot write() after finish()") RuntimeError: Cannot write() after finish()

Why is this happening? I referenced this question (second answer) I believe I am using the yield statement correctly.

class MainHandler(tornado.web.RequestHandler):
    executor = ThreadPoolExecutor(max_workers=64)

    def get(self):
        task = self.get_argument('task')
        self.serve(task)

    @tornado.gen.coroutine
    def serve(self, task):
        method = getattr(self, task)
        r = yield method()
        self.write(r)

    @run_on_executor
    def announcements(self):
        time.sleep(5)
        print("Done")
        with open('announcements.json') as announce_data:
            data = json.load(announce_data)
        print(data)
        return data

Solution

  • get must also be a coroutine:

    @gen.coroutine
    def get(self):
        task = self.get_argument('task')
        yield self.serve(task)
    

    In Tornado, only coroutines can call coroutines.