【问题标题】:How to query aws resources using boto3 and asyncio? Is this possible?如何使用 boto3 和 asyncio 查询 aws 资源?这可能吗?
【发布时间】:2020-10-05 18:17:28
【问题描述】:

我有一个现有的代码,它一个接一个地向 AWS 查询资源,并根据资源名称进行过滤。当前的实现是线性的,从每个资源的一个功能转移到下一个功能,创建各自的客户端并使用客户端查询 aws。这当然会耗费大量时间。是否可以以异步方式运行这些功能中的每一个?代码流看起来像下面的 sn-p,有更多的资源查询。 任何意见/建议都会有所帮助。

def query_acm():
    client = boto3.client('acm', region_name=region)
    client.get_paginator('list_certificates')
    # filter and write to file
def query_asg():
    client = boto3.client('autoscaling', region_name=region)
    paginator = client.get_paginator('describe_auto_scaling_groups')
    # paginate filter and write to file
def main():
    query_acm()
    query_asg()

【问题讨论】:

  • 你看到这里的讨论了吗? github.com/boto/botocore/issues/458
  • 感谢 @MarkB 分享链接,但这个问题已经开放了大约 3 年,人们似乎仍然对可用的解决方案有疑问。我确实探索了 aiobotocore 选项,但我这里的需求相对简单。

标签: python amazon-web-services asynchronous boto3 python-asyncio


【解决方案1】:

可以并行运行它们,但为此我建议您使用 python 内置的易于使用的 concurrent.futures 库。

from concurrent.futures import ThreadPoolExecutor, as_completed
import boto3

def query_acm():
    client = boto3.client('acm', region_name=region)
    client.get_paginator('list_certificates')
    # filter and write to file
def query_asg():
    client = boto3.client('autoscaling', region_name=region)
    paginator = client.get_paginator('describe_auto_scaling_groups')
    # paginate filter and write to file

def main():

    with concurrent.futures.Executor() as executor:
        futures = [executor.submit(query_acm), executor.submit(query_asg)]

    for f in as_completed(futures):
        # Do what you want with f.result(), for example:
        print(f.result())

您也可以为每个函数调用传递参数并获取响应。 Read more 或在 concurrent.futures 上关注 some examples

【讨论】:

  • 谢谢,这一次就成功了。我在使用 concurrent.futures.Executor() 作为执行程序调用的方法上有一个装饰器 @write_to_file:futures = [executor.submit(query_acm), executor.submit(query_asg)] 代码现在只能在没有装饰器的情况下工作。与装饰者一起,它永远在等待。我想有一个僵局。那里有什么见解吗?也感谢您分享您的详细帖子。如何让我的装饰器与并发一起工作?
  • @Jey,不客气。将多处理与具有装饰器的函数一起使用时存在问题。你可以使用没有装饰器的包装器函数,最终调用你的装饰器函数。
  • 是的,我尝试了同样的方法并且成功了。感谢和欢呼队友!
猜你喜欢
  • 2021-07-01
  • 2019-12-24
  • 1970-01-01
  • 2022-11-05
  • 2022-11-21
  • 2022-12-15
  • 2021-05-24
  • 2011-04-07
  • 1970-01-01
相关资源
最近更新 更多