python - 大多数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当我说我想重试时,我不想要这样的东西:异常后如何重试?
解决方案
只需创建一个可重复使用的装饰器!
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)
推荐阅读
- scala - Spark 在 foreachRDD 操作中抛出不可序列化异常
- python - 如何修复:删除 JSON 文件中的重复项并写入新文件
- python - 使用python从文本文件末尾读取n行
- scala - 如何通过scala中的类方法传递类型参数?
- android - 如何在 Android XAML 应用程序(Xamarin.Forms)中获取加速度计值
- c++ - DirectX - 启用深度缓冲区后没有渲染
- javascript - 如何使用 Javascript 使用每个元素自己的高度将边距底部添加到具有类的所有元素?
- r - 是否有 R 函数对数据框进行排序
- javascript - 最后怎么去掉
- 孩子连同它的本地存储?
- javascript - 事件中的流类型细化