[Answered ]-Tornado + Momoko. Restart corrupted connection

2👍

Temporary solution – close connection, if error happened in it. For it, let’s create class inspired by momoko.Op:

class OpWithFallback(gen.Task):
    """
    Run a single asynchronous operation.

    Behaves like `tornado.gen.Task`_, but raises an exception (one of Psycop2's
    exceptions_) when an error occurs related to Psycopg2 or PostgreSQL.

    Closes connection with error.

    .. _exceptions: http://initd.org/psycopg/docs/module.html#exceptions
    .. _tornado.gen.Task: http://www.tornadoweb.org/documentation/gen.html#tornado.gen.Task
    """
    def get_result(self):
        (result, error), _ = super(OpWithFallback, self).get_result()
        if error:
            self.fallback(error, result)
        return result

    def fallback(self, error, result):
        log.warning('Closing dead connection or connection with idle transaction: %s' % result.connection)
        result.connection.close()
        raise error

And let’s use it like:

result = yield OpWithFallback(self.db.execute, sql, [])

Leave a comment