首页 > 解决方案 > 大多数pythonic尝试的方式,除了,重试一次

问题描述

我正在寻找尝试命令的最pythonic方式,如果发生错误并通过运行准备命令然后运行原始命令来重试。特别是在我的情况下,我希望将表写入数据库,捕获是否抛出“模式不存在”错误,然后尝试创建模式并重试写入表。然后,如果写表再次出错,我不想抓住它。

到目前为止,我有(示意性地):

try:
    write_to_table(table, schema)
except sqlalchemy.exc.ProgrammingError:
    create_schema(schema)
    write_to_table(table, schema)

这可以满足我的要求,但似乎有点偏离,可能是因为我正在复制 write_to_table()。

那么执行上述操作的最pythonic方式是什么?

PS当我说我想重试时,我不想要这样的东西:异常后如何重试?

标签: python

解决方案


只需创建一个可重复使用的装饰器!

def retry(func):
        '''
        Decorator.
        If the decorated function fails with an exception 
        calls it again after a random interval.
        '''
        def _retry(*args,**kwargs):
            max_retries = 1
            for i in range(max_retries):
                try:
                    value = func(*args,**kwargs)
                    return value
                except sqlalchemy.exc.ProgrammingError as e:
                    print('function:[{}({},{})] Failed with error: {} . Retrying...'.format(func.__name__,str(*args),str(kwargs),str(e)))
                    time.sleep(random.uniform(1,3))
            print("Max_retries({}) exceeded for function {}".format(max_retries,func.__name__))
        return _retry

通过使用上面的装饰器,您还可以配置重试次数和重试间隔,您可以执行以下操作:

@retry
write_to_table(table, schema)

推荐阅读