pyodbc:如何重试从瞬时错误中恢复? [英] pyodbc: How to retry to recover from Transient errors?

查看:156
本文介绍了pyodbc:如何重试从瞬时错误中恢复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Flask上托管了一个API.它在Tornado服务器后面运行.发生的情况是,有时对UI所做的更改未反映在数据库中.另外,我正在运行的一些脚本给出了以下三个错误中的任何一个:

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:

  1. pyodbc.Error :("08S01","[08S01] [Microsoft] [ODBC SQL Server驱动程序]通信链接失败(0)(SQLExecDirectW)")
  2. pyodbc.Error :("01000","[01000] [Microsoft] [ODBC SQL Server驱动程序] [DBNETLIB] ConnectionWrite(send()).(10054)(SQLExecDirectW)")
  3. pyodbc.Error :("01000","[01000] [Microsoft] [ODBC SQL Server驱动程序] [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:如何重试从瞬时错误中恢复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆