AWS Lambda 在 S3 存储桶中创建文件夹 [英] AWS Lambda create folder in S3 bucket

查看:48
本文介绍了AWS Lambda 在 S3 存储桶中创建文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Lambda,它会在文件上传到 S3-A 存储桶并将这些文件移动到另一个存储桶 S3-B 时运行.挑战是我需要在 S3-B 存储桶中创建一个文件夹,其中包含上传文件的相应日期,并将文件移动到该文件夹​​中.任何帮助或想法都非常感谢.可能听起来很混乱,请随时提出问题.谢谢!

I have a Lambda that runs when files are uploaded to S3-A bucket and moves those files to another bucket S3-B. The challenge is that I need create a folder inside S3-B bucket with a corresponding date of uploaded files and move the files to the folder. Any help or ideas are greatly apprecited. It might sound confusing so feel free to ask questions.Thank you!

推荐答案

这是一个可以由 Amazon S3 事件触发并将对象移动到另一个存储桶的 Lambda 函数:

Here's a Lambda function that can be triggered by an Amazon S3 Event and move the object to another bucket:

import json
import urllib
from datetime import date
import boto3

DEST_BUCKET = 'bucket-b'

def lambda_handler(event, context):
    
    s3_client = boto3.client('s3')
    
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'])


    dest_key = str(date.today()) + '/' + key
    
    s3_client.copy_object(
        Bucket=DEST_BUCKET,
        Key=dest_key,
        CopySource=f'{bucket}/{key}'
        )

唯一需要考虑的是时区.Lambda 函数以 UTC 运行,您的时区中的日期可能略有不同,因此您可能需要相应地调整时间.

The only thing to consider is timezones. The Lambda function runs in UTC and you might be expecting a slightly different date in your timezone, so you might need to adjust the time accordingly.

这篇关于AWS Lambda 在 S3 存储桶中创建文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆