正确使用 Python 中的装饰器重试建立“mysql.connector”连接

问题描述 投票:0回答:0

所以我有一个脚本,它对 sql 数据库进行了很多不同的调用,并使用这个抽象连接函数来创建一个 mysql.connection 对象。该程序连接到的数据库在我的控制之外有相当规律的辍学。我打算这样做的只是在日志中打印一行说“嘿,数据库已关闭,将在几秒钟内重试”但实际发生的是 mysql.connector.Error 在

else: 处抛出异常
 
中的行,但仍然返回 None
get_connection()
变量并使整个程序崩溃。

sql_connection

# A decorator that catches Exceptions and tries to execute the query again
def retry(func):

    def wrapper(*args, **kwargs):

        # Number of total retry events
        attempts = 5
        # Interval (in seconds) between retry events
        interval = 30

        for i in range(attempts):
            try:
                return func(*args,**kwargs)
            except Exception as e: # Not checking for specific errors
                if i == attempts - 1:
                    raise Exception(e)
                else:
                    logger.info('Could not execute db connection. Trying again in another : {} secs'.format(interval))
                    time.sleep(interval)
                    continue
    return wrapper


@retry
def get_connection():

    try:
        sql_connection = mysql.connector.connect(host = h, user = u, password = p, database = d)
    except mysql.connector.Error as err:
        if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
            logger.error("Invalid user name or password!")
        elif err.errno == errorcode.ER_BAD_DB_ERROR:
            logger.error("Database does not exist!")
        else:
            logger.error(f"Unspecified error connecting to db: {err}")
    else:
        return sql_connection
函数基本上是从官方文档中批量提取的,而
get_connection()
函数非常通用,如许多“操作方法”文章中所述。根据错误输出,它就像抛出异常一样,但
retry()
仍然在
get_connection()
变量中返回 NoneType 值:

sql_connection

第二个错误行是调用函数尝试从返回的

ERROR - Unspecified error connecting to db: 2003: Can't connect to MySQL server on '123.456.789.10' (113 No route to host)
ERROR - 'NoneType' object has no attribute 'cursor'
获取游标的地方,即使 try/except/else 抛出异常..基本上它是这样的:

sql_connection

我误解了

conn = get_connection()
cursor = conn.cursor()
sql_query = "SELECT * FROM my_table"
cursor.execute(sql_query)
print(cursor.fetchall()
条款吗?只有在存在NO
else:
问题时才应该执行,对吗?我有一种感觉,我只是没有用装饰器来处理数据流,我在这里做了一些非常愚蠢的事情..

python-3.x error-handling python-decorators mysql-connector
© www.soinside.com 2019 - 2024. All rights reserved.