日々精進

新しく学んだことを書き留めていきます

boto3のlist_objects_v2は最大1000オブジェクトまでしか取得出来ない

1001以上取得したい場合はループを回す必要がある。例は以下。

    def list_all_contents(self, prefix: str = ''):
        next_token = ''
        base_kwargs = {
            'Bucket': self.bucket_name,
            'Prefix': prefix,
        }
        all_contents: List[dict] = []
        while next_token is not None:
            kwargs = base_kwargs.copy()
            if next_token != '':
                kwargs.update({'ContinuationToken': next_token})
            objs = self.bucket.meta.client.list_objects_v2(**kwargs)
            all_contents.extend(objs.get('Contents'))
            next_token = objs.get('NextContinuationToken')
        return all_contents

参考:

stackoverflow.com