Search code examples
pythonruntime-errortornado

Python tornado stop execution with finish()


I am relatively new to tornado and I am trying to stop execution of a method if a condition passes, otherwise it should go on to the next line of code (similar to return)

This is the part my code where I am stuck,

class PostMatchHandler(BaseRequestHandler):
    result1 = "some sql query".execute()
    if not result1:
        response.update({'info': 'Levels Completed', 'status': settings.STATUS_200})
        self.write(response)
        self.finish()

    else:
        result1 = result1[0]
        do_something()
    self.write(response)

BaseRequestHandler is:

class BaseRequestHandler(tornado.web.RequestHandler):
    """
    Base Class for all the future classes
    Activities like logging should be done in this class.
    Allow cors request in this class
    """

    def set_default_headers(self):
        print "setting headers!!!"

    def write_error(self, status_code, **kwargs):
        response = {}
        handle_error_messages..
        self.write(response)

    @staticmethod
    def extract_psycopg2_integrity_error(error):
        return error.message.split("Key")[1].replace("(", "").replace(")", "").split(".")[0].replace("=", " ")

    def prepare(self):
        logging.debug(
            "[info] Class {} via {} with body {}".format(self.__class__.__name__, self.request.uri, self.request.body))

So, here if result1 is empty, then it should finish the API's execution and return. But I am getting this error RuntimeError: Cannot write() after finish()

How shall I stop the execution.


Solution

  • You don't need "self.finish", it completes Tornado's writing of the response but it does not stop execution of your function. To stop execution of a function, add a return statement:

    def get(self)
        result1 = "some sql query".execute()
        if not result1:
            response.update({'info': 'Levels Completed', 'status': settings.STATUS_200})
            self.write(response)
            return  # <-- here
        else:
            result1 = result1[0]
            do_something()
        self.write(response)
    

    The other option is to indent the final line so it remains within the "else" clause:

    def get(self):
        result1 = "some sql query".execute()
        if not result1:
            response.update({'info': 'Levels Completed', 'status': settings.STATUS_200})
            self.write(response)    
        else:
            result1 = result1[0]
            do_something()
            self.write(response)  # indented 4 more spaces