pyodbc: How to retry to recover from Transient errors?(pyodbc:如何重试从瞬态错误中恢复?)
问题描述
我在 Flask 上托管了一个 API.它在 Tornado 服务器后面运行.发生的情况是有时对 UI 所做的更改未反映在数据库中.此外,我运行的一些脚本会出现以下 3 个错误中的任何一个:
I've an API hosted on Flask. It runs behind a Tornado server. What is happening is that sometimes changes made on the UI are not reflected in the database. Also a few of the scripts I have running gives any of the 3 following errors:
- pyodbc.Error: ('08S01', '[08S01] [Microsoft][ODBC SQL Server Driver]通信链接失败 (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 代码片段:
This is the snippet of my Flask API code:
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 处理瞬时错误.请帮忙.
Is there any retry logic I can add on the cursor.execute line? I've no idea how to deal with transient errors with python. Please help.
推荐答案
根据我的经验,我觉得可能你可以尝试使用下面的代码来实现重试逻辑.
Per my experience, I think may be you can try to use the code below to implement the retry logic.
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)
希望有帮助.
这篇关于pyodbc:如何重试从瞬态错误中恢复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:pyodbc:如何重试从瞬态错误中恢复?
基础教程推荐
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 无法解决整理冲突 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
