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 存储桶对象。谢谢你。
I have tried resolving your errors and 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()