【问题标题】:How to download and upload s3 objects in same bucket (different prefixes) with boto3如何使用 boto3 在同一存储桶(不同前缀)中下载和上传 s3 对象
【发布时间】:2019-12-21 07:04:23
【问题描述】:

我正在使用 AWS lambda 函数实现图像处理算法。我想从 S3 存储桶中的“子文件夹”/前缀收集图像,使用 boto3 运行我的算法,并将处理后的图像上传到同一 S3 存储桶中的不同“子文件夹”/前缀。

我还没有成功地在同一个 S3 存储桶内或在前缀下移动图像。我可以使用 boto3 资源或客户端从存储桶中的“根”文件夹下载图像,然后将处理后的图像上传到不同的存储桶。但是,我未能成功访问“子文件夹”/前缀中的图像。

def lambda_handler(event, context):
    for record in event['Records']:
    bucket = record['s3']['bucket']['name']
    key = record['s3']['object']['key'] 
    file_path = '/tmp/' + key

    s3_client.download_file(bucket, key, file_path)

    # call image processing algorithm here

    s3_client.upload_file(file_path, 'bucket/folder_a/folder_b', key)

与事件一起传递的密钥是'folder_a/folder_b/IMG_X.jpg'。我一直收到文件未找到错误。

【问题讨论】:

    标签: python amazon-s3 aws-lambda boto3


    【解决方案1】:

    您似乎将路径作为存储桶名称的一部分。将其添加到键的开头,例如:

    s3_client.upload_file(file_path, 'bucket', 'folder_a/folder_b' + key)
    

    【讨论】:

    • 将文件夹结构从存储桶中分离出来。有必要传递整个文件夹结构来指示您希望文件在 S3 存储桶中的存储位置。谢谢!
    【解决方案2】:

    我收到文件未找到错误,因为 boto3 不喜欢我将密钥传递给 download_file 函数的方式。我没有传递具有整个文件夹结构的密钥(如 S3 控制台显示的密钥),而是传递了基本文件名。

    对于upload_file 函数,需要传递您希望将文件存储在 S3 存储桶中的位置的整个文件夹结构(带有文件名)。

    s3_client = boto3.client('s3')
    
    def lambda_handler(event, context):
    
        for record in event['Records']:
            try:
                bucket = record['s3']['bucket']['name']
                key = record['s3']['object']['key']
                file_name = key.split('/')[-1]
                file_path = '/tmp/' + file_name
    
                s3_client.download_file(bucket, key, file_path)
    
                # call image processing algorithm here
    
                s3_client.upload_file(file_path, <target bucket>, 'folder_a/folder_b' + file_name)
    
                return {
                    'statusCode': 200,
                    'body': 'Success'
                }
            except Exception as e:
                logger.info(e)
                return {
                    'statusCode': 400,
                    'body': 'Error'
                }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-22
      • 2018-01-04
      • 2020-07-07
      相关资源
      最近更新 更多