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

Jey*_*Jey 4 python asynchronous amazon-web-services python-asyncio boto3

我有一个现有代码,可以根据资源名称依次查询 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()
Run Code Online (Sandbox Code Playgroud)

ams*_*msh 7

可以并行运行它们,但为此我建议您使用 python 内置的易于使用的并发.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())

Run Code Online (Sandbox Code Playgroud)

您也可以传递参数并获取每个函数调用的响应。阅读更多内容或遵循并发.futures 上的一些示例