【问题标题】:How I will get response of success in aws file upload on s3 bucket using boto3?如何使用 boto3 在 s3 存储桶上上传 aws 文件时获得成功响应?
【发布时间】:2019-06-06 04:08:39
【问题描述】:

我知道如何使用 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 作为响应。所以请帮助我,我们将不胜感激。

【问题讨论】:

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


    【解决方案1】:

    upload_file() 函数不返回值。

    如果上传出现问题,会引发异常。

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

    【讨论】:

    • 我会尽快检查,如果可行,请接受您的回答。感谢您的回复。
    【解决方案2】:

    或者,您可以使用 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': '...'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-17
      • 2015-07-23
      • 2018-04-25
      • 2023-04-05
      • 1970-01-01
      • 2015-08-24
      • 2021-02-10
      相关资源
      最近更新 更多