AWS-Lambda 函数 (Python) 从 S3 复制文件 - 执行操作 - 将输出存储在另一个 S3 中

问题描述 投票:0回答:1

我正在寻求一些指导,如果有人可以引导我走向正确的方向。

场景:必须用 Python 编写一个能够执行以下任务的 Lambda 函数;

  1. 当文件复制到 S3 存储桶 A 时会触发 Lambda。
  2. Lambda 能够从文件名或内容中区分出触发什么逻辑。
  3. Lambda 将文件复制到 S3 存储桶 B。
  4. Lambda 根据文件名或内容进行处理,并将输出存储在 S3 存储桶 C 中的另一个文件中。

对于上述内容,如果您可以指导我们可以使用哪个Python库,任何可以使这项任务变得更容易的函数。我对 Python 没有太多经验,所以任何示例代码也将非常感激。

python amazon-s3 aws-lambda
1个回答
0
投票

此代码都可以在 lambda 处理函数中使用 python boto3 库运行 (

def lambda_handler(event, context):
)。 您必须设置 s3 客户端才能复制对象或写入存储桶

s3 = boto3.client('s3')

1.当文件复制到 S3 存储桶 A 时会触发 Lambda。

# Get the S3 bucket name and object key from the event
bucket_name = event['Records'][0]['s3']['bucket']['name']
object_key = event['Records'][0]['s3']['object']['key']

if bucket_name == 'A':
    # code 

2. Lambda 能够从文件名或内容区分触发什么逻辑。

# Check if the file ends with "_passed.csv" and the bucket name is 'A'
if bucket_name == 'A' and object_key.endswith('_passed.csv'):
    # trigger logic here

3. Lambda 将文件复制到 S3 存储桶 B。

copy_source = {'Bucket': 'A', 'Key': 'folder/file'}
s3.copy_object(CopySource = copy_source, Bucket = 'B', Key = 'folder/file')

4. Lambda 根据文件名或内容进行处理,并将输出存储在 S3 存储桶 C 中的另一个文件中。

使用 if 语句完成的选择性逻辑(如上所示),将输出存储在 s3 存储桶 C:

content="output to put in another file"
s3.Object('C', 'put_in_bucket_C.txt').put(Body=content)
© www.soinside.com 2019 - 2024. All rights reserved.