-->

RuntimeError: Cannot write() after finish(). May b

2019-08-31 07:41发布

问题:

I am getting the above error while making a post request in the tornado server .

I have a class like

class RestRequestHandler(RequestHandler):

    def async_get(self, *args, **kwargs):
        pass
    def async_post(self, *args, **kwargs):
        pass

The above class I am importing into another py file

class get_question_details(RestRequestHandler):

    def async_post(self, activity_id, attempt_id, quiz_id, question_id,
                   questionusage_id, slot, user_name, courseshortname):
        client = get_moodle_client()

When I am making this request I am getting the warning like

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/tornado/ioloop.py", line 421, in _run_callback
    callback()
  File "/usr/local/lib/python2.7/dist-packages/gameonapi/server/rest.py", line 142, in async_post_callback
    self.return_ok(result)
  File "/usr/local/lib/python2.7/dist-packages/gameonapi/server/rest.py", line 214, in return_ok
    self.write (result)
  File "/usr/local/lib/python2.7/dist-packages/tornado/web.py", line 489, in write
    raise RuntimeError("Cannot write() after finish().  May be caused "
RuntimeError: Cannot write() after finish().  May be caused by using async operations without the @asynchronous decorator.

From the error I understood that problem causing because I am not using the tornado @asynchronous but after using that also still I am getting the same warning .

Please tell me what might I am doing wrong here .

回答1:

Maybe you should register Post method for your class, because I dont see how tornado may handle POST request in your way. Check this question. How to use POST method in Tornado?



回答2:

If you do not use the @asynchronousdecorator the self.finish() function would be called automatically before the function is complete

What you should have is

class RestRequestHandler(RequestHandler):

@tornado.web.asynchronous
def async_get(self, *args, **kwargs):
    self.write('ok')
    self.finish()

@tornado.web.asynchronous
def async_post(self, *args, **kwargs):
    self.write('ok')
    self.finish()

This way the system gives you the chances to write out whatever you wish to write. When finished writing you will need to call the self.finish method to tell the system you are done.