pyodbc:如何重试以从暂时性错误中恢复?

2024-05-20 00:01:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我在烧瓶上有一个API。它运行在龙卷风服务器后面。所发生的情况是,有时对UI所做的更改不会反映在数据库中。另外,我运行的一些脚本会出现以下3个错误:

  1. pyodbc。错误:('08S01','[08S01][Microsoft][ODBC SQL Server驱动程序]通信链接失败(0)(SQLExecDirectW)'
  2. pyodbc.Error:('01000','[01000][Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionWrite(send())。(10054)(SQLExecDirectW)')
  3. 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处理暂时的错误。请帮忙。


Tags: addapiparsersqlservertype错误args
1条回答
网友
1楼 · 发布于 2024-05-20 00:01:08

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

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)

希望有帮助。

相关问题 更多 >