简体   繁体   English

使用 Lambda/Python 将多个文件上传到 S3

[英]Upload multiple files to S3 using Lambda/Python

so I'm writing a Lambda function that is triggered by events from DynamoDB Streams, and I want to write these events to S3 (to create a data lake).所以我正在编写一个由来自 DynamoDB Streams 的事件触发的 Lambda 函数,我想将这些事件写入 S3(以创建数据湖)。 but this code is only uploading the same json file.但此代码仅上传相同的 json 文件。 How can I upload multiple files into s3 without overwriting this one?如何在不覆盖此文件的情况下将多个文件上传到 s3?

   import boto3
   import json
   
   s3 = boto3.client('s3')
   
   def lambda_handler(event, context):
       
     bucket ='bto-history'
     dynamodb = boto3.resource('dynamodb')
     tableUsers = dynamodb.Table('Users')
       
     jsonToUpload = event['Records']
   
     uploadFile = bytes(json.dumps(jsonToUpload).encode('UTF-8'))
     
     jsonToUpload = "userUpdate" + ".json"
   
     s3.put_object(Bucket=bucket, Key=jsonToUpload, Body=uploadFile)
   
     
     return {
       'statusCode': 200,
       'body': event
       }

You didn't say, but I'm guessing that you are writing a Lambda function that is triggered by events from DynamoDB Streams, and you want to write those events to S3.您没有说,但我猜您正在编写一个由来自 DynamoDB Streams 的事件触发的 Lambda 函数,并且您想将这些事件写入 S3。

If you want to maintain multiple files/objects in S3 then you need to give them unique keys.如果要在 S3 中维护多个文件/对象,则需要为它们提供唯一键。 Writing to userUpdate.json will simply overwrite any existing object with that key (unless you have versioning enabled, which I presume you don't).写入 userUpdate.json 只会用该键覆盖任何现有对象(除非您启用了版本控制,我认为您没有启用)。

So, create a unique object key each time.因此,每次都创建一个唯一的对象键。 You could insert a timestamp in milliseconds (or other), which is probably unique.您可以以毫秒(或其他)为单位插入时间戳,这可能是唯一的。 Or you could insert a UUID.或者你可以插入一个 UUID。

Worth asking: why do you want to store the DynamoDB Streams events in S3?值得一问:为什么要将 DynamoDB Streams 事件存储在 S3 中?

event['Records'] is a list which you need to iterate over. event['Records']是一个需要迭代的列表。 See https://docs.aws.amazon.com/lambda/latest/dg/with-ddb.html请参阅https://docs.aws.amazon.com/lambda/latest/dg/with-ddb.html

Each entry holds info about a dynamodb event.每个条目都包含有关 dynamodb 事件的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM