首页 文章

pyodbc:如何重试从瞬态错误中恢复?

提问于
浏览
2

我在Flask上托管了一个API . 它运行在Tornado服务器后面 . 发生的事情是,有时在UI上进行的更改不会反映在数据库中 . 我运行的一些脚本也提供了以下3个错误中的任何一个:

  • pyodbc.Error:('08S01','[08S01] [Microsoft][ODBC SQL Server Driver]Communication link failure (0) (SQLExecDirectW)')

  • pyodbc.Error:('01000','[01000] [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionWrite (send()). (10054) (SQLExecDirectW)')

  • pyodbc.Error:('01000','[01000] [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionRead (recv()). (10054) (SQLExecDirectW)')

这是我的Flask API代码的片段:

class Type(Resource):

    def put(self):
        parser = reqparse.RequestParser()
        parser.add_argument('id', type = int)
        parser.add_argument('type', type = int)
        args = parser.parse_args()

        query = """
        UPDATE myDb SET Type = ? WHERE Id = ?
        """

        connection = pyodbc.connect(connectionString)
        cursor = connection.cursor()
        cursor.execute(query, [args['type'], args['id']])
        connection.commit()
        cursor.close()
        connection.close()

api.add_resource(Type, '/type')

我可以在cursor.execute行上添加任何重试逻辑吗?我不知道如何使用python处理瞬态错误 . 请帮忙 .

1 回答

  • 7

    根据我的经验,我认为您可以尝试使用下面的代码来实现重试逻辑 .

    import time
    
    retry_flag = True
    retry_count = 0
    while retry_flag and retry_count < 5:
      try:
        cursor.execute(query, [args['type'], args['id']])
        retry_flag = False
      except:
        print "Retry after 1 sec"
        retry_count = retry_count + 1
        time.sleep(1)
    

    希望能帮助到你 .

相关问题