check if a key exists in a bucket in s3 using boto3

前端 未结 24 2814
花落未央
花落未央 2020-11-28 19:03

I would like to know if a key exists in boto3. I can loop the bucket contents and check the key if it matches.

But that seems longer and an overkill. Boto3 official

24条回答
  •  -上瘾入骨i
    2020-11-28 19:50

    I noticed that just for catching the exception using botocore.exceptions.ClientError we need to install botocore. botocore takes up 36M of disk space. This is particularly impacting if we use aws lambda functions. In place of that if we just use exception then we can skip using the extra library!

    • I am validating for the file extension to be '.csv'
    • This will not throw an exception if the bucket does not exist!
    • This will not throw an exception if the bucket exists but object does not exist!
    • This throws out an exception if the bucket is empty!
    • This throws out an exception if the bucket has no permissions!

    The code looks like this. Please share your thoughts:

    import boto3
    import traceback
    
    def download4mS3(s3bucket, s3Path, localPath):
        s3 = boto3.resource('s3')
    
        print('Looking for the csv data file ending with .csv in bucket: ' + s3bucket + ' path: ' + s3Path)
        if s3Path.endswith('.csv') and s3Path != '':
            try:
                s3.Bucket(s3bucket).download_file(s3Path, localPath)
            except Exception as e:
                print(e)
                print(traceback.format_exc())
                if e.response['Error']['Code'] == "404":
                    print("Downloading the file from: [", s3Path, "] failed")
                    exit(12)
                else:
                    raise
            print("Downloading the file from: [", s3Path, "] succeeded")
        else:
            print("csv file not found in in : [", s3Path, "]")
            exit(12)
    

提交回复
热议问题