Mee*_*101 2 python api amazon-web-services amazon-elastic-beanstalk
我有一些 lambda 函数,它们正在用 python 编写多个 AWS Elastic beanstalk API 调用。一切正常。但自最近几天以来,我们收到了节流错误。在与 AWS 讨论后,他们建议在代码中添加指数退避逻辑。因此,如果受到限制,将以增量间隔重试相同的 API 调用。我明白他们在说什么以及它是如何工作的,但我不明白如何添加到我的代码中。他们有 CLI 文档,但没有 API,如下所示:http://docs.aws.amazon.com/general/latest/gr/api-retries.html
有人可以给我一个简单的例子,如果它像我在代码中使用的一个 API 调用一样受到限制,我们如何映射 API 调用的响应并重试,如下所示,
import boto3
conn = boto3.client('elasticbeanstalk')
response = conn.describe_environments(EnvironmentNames=["xyz"])
return response
Run Code Online (Sandbox Code Playgroud)
我知道使用 if 条件执行此操作的简单方法,通过检查响应是否“超出速率”,使用 while do i think 我可以实现此目的。但我想检查 CLI 示例中提供的内容,如何对 API 执行类似操作?
任何帮助,将不胜感激!
您可以使用代理对象来包装任何 AWS 客户端对象并向代理对象添加一些重试逻辑:
from botocore.exceptions import ClientError
import retrying
import wrapt
class RetriedClient(wrapt.ObjectProxy):
"""Add retry logic to a boto3 client.
Wait 2^x * 1000 milliseconds between each retry, up to 10 seconds,
then 10 seconds afterwards.
"""
def is_throttling_error(exception):
"""Botocore throws just a generic ClientError exception."""
return isinstance(exception, ClientError) \
and "RequestLimitExceeded" in exception.response
@retrying.retry(
wait_exponential_multiplier=1000,
wait_exponential_max=10000,
retry_on_exception=is_throttling_error)
def __getattr__(self, name):
return getattr(self.__wrapped__, name)
# Create a boto3 client to Cloudformation
cf_client = boto3.client('cloudformation')
# Add exponential backoff retries to all client methods
wrapped_cf_client = RetriedClient(cf_client)
Run Code Online (Sandbox Code Playgroud)
然后你就可以wrapped_cf_client像平常使用 boto3 的内置客户端一样使用:
resp = wrapped_cf_client.describe_stacks()
Run Code Online (Sandbox Code Playgroud)
弃用说明:
在较新版本中,botocore有一种更好的方法来配置 boto3 SDK 的重试逻辑。1.6.0这从以下版本开始工作botocore:
resp = wrapped_cf_client.describe_stacks()
Run Code Online (Sandbox Code Playgroud)