Search code examples
sqlalchemycherrypypymssql

sqlalchemy pymssql "connection reset by peer" recovery


I'm running a cherrypy webservice and wondering what the best option is to recover from "connection reset by peer" for a pymssql connection via sqlalchemy. Right now I have to restart the webservice.


Solution

  • This seems to be a bug in the is_disconnect() method for pymssql where it ignore TCP connection and timeout failures, leaving the cursor in an unhappy state; see http://www.sqlalchemy.org/trac/ticket/2172. For now, you can monkey-patch as:

    from sqlalchemy.dialects.mssql import pymssql
    
    def is_disconnect(self, e):
        for msg in (
            "20003",
            "20004",
            "Error 10054",
            "Not connected to any MS SQL server",
            "Connection is closed"
            ):
            if msg in str(e):
                return True
        else:
            return False
    
    pymssql.MSDialect_pymssql.is_disconnect = is_disconnect