繁体   English   中英

如何使用 boto3 和 asyncio 查询 aws 资源? 这可能吗?

[英]How to query aws resources using boto3 and asyncio? Is this possible?

我有一个现有的代码,它一个接一个地查询 AWS 的资源,根据资源名称进行过滤。 当前的实现是线性的,从每个资源的一个功能转移到下一个功能,创建相应的客户端并使用客户端查询 aws。 这当然会消耗很多时间。 是否可以以异步方式运行这些函数中的每一个? 代码流看起来像下面的代码片段,其中包含更多资源查询。 任何输入/建议都会有所帮助。

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()

可以并行运行它们,但为此我建议您使用 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())

您也可以为每个函数调用传递参数并获得响应。 阅读更多内容或关注 concurrent.futures 上的一些示例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM