如何使用boto3在s3存储桶上的aws文件上传中获得成功的响应?

时间:2019-06-06 04:08:39

标签: python amazon-web-services amazon-s3 boto3

我知道如何使用boto3将文件上传到s3存储桶中。但是我在函数中使用了它,我想检查图像是否成功上传到s3存储桶,如果已上传,则要执行操作。

这是示例,

import boto3

def upload_image_get_url(file_name, bucket, key_name):

   s3 = boto3.client("s3")

   result = s3.upload_file(file_name, bucket, key_name) # Here I got none so How I will check like file is upoaded or not?

   if result == 'success' or result == True:
       response = "https://{0}.s3.us-east-2.amCCazonaws.com/{1}".format(bucket, key_name)
   else:
       response = False

   return response


所以我的要求很简单,例如,如果我成功上传文件,那么我将返回s3 url作为响应。所以请帮助我,您的帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

upload_file()函数不会返回值。

如果上传有问题,将会引发异常

例如,如果找不到要上传的本地文件,则会引发FileNotFoundError异常。 (试试看!)

答案 1 :(得分:0)

或者,您可以使用put_object()来返回字典:

import os.path
import boto3

def upload_image_get_url(file_name, bucket, key_name):

    s3 = boto3.client("s3")

    # Get the file name
    name = os.path.basename(file_name)

    # Format the key
    s3_key = '{0}/{1}'.format(key_name, name)

    # Send the file
    with open(file_name, 'rb') as fd:
        result = s3.put_object(
            Bucket=bucket,
            Key=s3_key,
            Body=fd
        )

    if result['ResponseMetadata']['HTTPStatusCode'] == 200:
       response = "https://{0}.s3.us-east-2.amCCazonaws.com/{1}".format(bucket, s3_key)
   else:
       response = False

   return response

结果将包含这些键:

'ResponseMetadata':
    'RequestId': '...'
    'HostId': '...'
    'HTTPStatusCode': 200
    'HTTPHeaders':
        'x-amz-id-2': '...'
        'x-amz-request-id': '...'
        'date': 'Fri, 15 Nov 2019 10:56:15 GMT'
        'x-amz-version-id': '...'
        'x-amz-server-side-encryption': 'AES256'
        'etag': '"..."'
        'content-length': '0'
        'server': 'AmazonS3'
    'RetryAttempts': 0
'ETag': '"..."'
'ServerSideEncryption': 'AES256'
'VersionId': '...'