12
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

boto3 で pagination が発生する API を良い感じに処理する

Posted at

結論

Client じゃなくて Paginator を使えば良い。

Paginators — Boto 3 Docs 1.9.210 documentation
https://boto3.amazonaws.com/v1/documentation/api/latest/guide/paginators.html

サンプル: CloudWatch Logs のロググループ一覧を取得したい場合

そもそも pagination を考慮できてない例

CloudWatchLogs — Boto 3 Docs 1.9.210 documentation
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/logs.html#CloudWatchLogs.Client.describe_log_groups

import boto3

client = boto3.client('logs')
response = client.describe_log_groups()
print(response)

describe_log_groups() の結果で全てのロググループを取得できない可能性があるので NG

Client で頑張る例

import boto3
client = boto3.client('logs')
response = client.describe_log_groups()
print(response)

while 'nextToken' in response:
    response = client.describe_log_groups(nextToken=response['nextToken'])
    print(response)

describe_log_groups() のレスポンスに nextToken が含まれる場合、while でループして続きを取得する方法。
まぁこれでも全でのロググループを取得できる。

Paginator 使う例

CloudWatchLogs — Boto 3 Docs 1.9.210 documentation
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/logs.html#CloudWatchLogs.Paginator.DescribeLogGroups

import boto3
client = boto3.client('logs')
paginator = client.get_paginator('describe_log_groups')

for page in paginator.paginate():
    print(page)

Client 使って while でループする方法と比較して、よりシンプルに書けた。

12
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?