簡體   English   中英

Python / Boto3 / 如何獲得帶有分頁的標簽列表?

[英]Python / Boto3 / How can i get a tag list with pagination?

我想使用 boto3 獲得一個 rds 和每個標簽列表,沒有 100 個限制。

這是獲取 rds 列表和每個標簽的代碼。

client = boto3.client('rds')
instances = client.describe_db_instances()['DBInstances']

for i in instances:
    db_instance_name = i['DBInstanceIdentifier']
    arn = i['DBInstanceArn']
    tags = client.list_tags_for_resource(ResourceName=arn)
    for item in tags['TagList']:
        if item['Key'] == 'Name':
            print(db_instance_name,item['Value'])

這是分頁的代碼。

def all_rds_instances(page_size=20):
    client = session.client('rds')
    marker = ""
    pool = []
    while True:
        for instance in pool:
            yield instance
        if marker is None:
            break
        result = client.describe_db_instances(MaxRecords=page_size, Marker=marker)
        marker = result.get("Marker")
        pool = result.get("DBInstances")

我怎樣才能結合這兩個代碼?

您只需要更改 for 循環以迭代您的 all_rds_instances 生成器。

您的腳本如下所示:

import boto3

client = boto3.client('rds')

def all_rds_instances(page_size=20):
    marker = ''
    pool = []
    while True:
        for instance in pool:
            yield instance
        if marker is None:
            break
        result = client.describe_db_instances(MaxRecords=page_size, Marker=marker)
        marker = result.get('Marker')
        pool = result.get('DBInstances')


for i in all_rds_instances():
    db_instance_name = i['DBInstanceIdentifier']
    arn = i['DBInstanceArn']
    tags = client.list_tags_for_resource(ResourceName=arn)
    for item in tags['TagList']:
        if item['Key'] == 'Name':
            print(db_instance_name, item['Value'])

當您使用yield關鍵字時,您的 function 將成為生成器,並且它的工作方式與 python 中的任何可迭代對象相同。

關於生成器如何在這里工作有一些很酷的答案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM