sqlalchemy pymssql “connection reset by peer” reco

2019-06-14 02:00发布

问题:

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.

回答1:

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