代码之家  ›  专栏  ›  技术社区  ›  Scarface Jr

如何获取S3中具有Key Error和异常的对象列表

  •  0
  • Scarface Jr  · 技术社区  · 2 年前
    I am new to this AWS boto3 concepts .The below code is giving a Key error  and some exception  that i am trying to execute can someone look to it and try to solve if any errors?
    
    import boto3
    
    def list_s3_objects(bucket_name):
        s3 = boto3.client('s3')
        objects = []
        try:
            response = s3.list_objects_v2(Bucket=bucket_name)
            for obj in response['Contents']:
                objects.append(obj['Key'])
        except Exception as e:
            print(f"An error occurred in the following ie,: {e}")
        return objects
    
    def main():
        bucket_name = 'name of my bucket'
        objects = list_s3_objects(bucket_name)
        print("S3 Objects to be created are:")
        for obj in objects:
            print(obj)
    
    if __name__ == "__main__":
        main()
    

    我尝试了不同的异常处理,甚至我的登录详细信息都是正确的。但它也显示出关键错误。我只是想打印我的s3 bucket对象。

    1 回复  |  直到 2 年前
        1
  •  0
  •   Anudeep K S    2 年前
    The below code lists the s3 objects as you have specified. Here I have added the paginator and botocore.exceptions for checking exception.  Thank you
    
    import boto3
    from botocore.exceptions import ClientError
    
    def list_s3_objects(bucket_name):
        s3 = boto3.client('s3')
        objects = []
        try:
            paginator = s3.get_paginator('list_objects_v2')
            for page in paginator.paginate(Bucket=bucket_name):
                if 'Contents' in page:
                    for obj in page['Contents']:
                        objects.append(obj['Key'])
        except ClientError as e:
            print(f"Error occurred is: {e}")
        return objects
    
    def main():
        bucket_name = 'my-bucket'
        objects = list_s3_objects(bucket_name)
        print("S3 Objects are :")
        for obj in objects:
            print(obj)
    
    if __name__ == "__main__":
        main()
    
    推荐文章