首页 > 解决方案 > 通过 AWS (boto3) 调用使用 Tenacity

问题描述

我在使用 boto3 调用 AWS 时遇到间歇性 RateLimitExceeded 错误。在下面的示例中,调用 instance.all() 或 i.vpc.tags 都可能由于速率限制而失败:

 for i in instance.all():
     tags = i.vpc.tags

通常,我在自己的函数中使用坚韧作为装饰器,但显然不能通过这个调用来完成,因为它来自导入的库。如果它不在 for 循环中,我可以使用重试功能,如下所示:

r = tenacity.Retrying(
    reraise=True, 
    wait=tenacity.wait_random_exponential(multiplier=1, max=60), 
    stop=tenacity.stop_after_delay(130))

r.call(call_wrapped_in_tenacity())

那么,有没有办法在保持重试能力的同时,将这两个调用包装到 AWS 而不为每个调用构建一个新函数?

标签: python-3.xamazon-web-serviceserror-handlingboto3

解决方案


如果创建自己的函数超出范围,那么这是我发现解决此问题的唯一方法。基本上,当您创建 boto3 客户端时,您会在 boto 配置中传递对您自己设置的引用,如下所示:

from botocore.config import Config
config = Config(retries=dict(max_attempts=20))
ec2_client = boto3.client('ec2', config=config)

推荐阅读