在 Lambda 中使用 Python 创建一个新文件,写入并上传到 S3

Creating a new file, writing to it and uploading to S3 using Python in Lambda

我正在尝试在 AWS Lambda 中使用 Python 创建一个新文件并写入该文件,然后上传到 S3 存储桶。我希望每个文件名都基于变量是唯一的。在本例中为 submission_id。

import json
import sys
import logging
import boto3

client = boto3.client('s3')

解析来自 webhook API 调用的数据(一切正常)

def lambda_handler(event, context):
     form_data = json.loads(event['body'])
     form_id = (form_data['FormID'])
     submission_id = (form_data['UniqueID'])

创建包含结果的新文件并上传到 S3。

想使用 submission_id 作为文件名变量。

     data_file = open('/tmp/submission_id' + '.txt', 'w+')
     data_file.write(str(form_data))
     data_file.close()

将文件上传到 S3 存储桶

     client.upload_file('/tmp/submission_id', 'mb-sentiment' , 'data_file')

我收到的错误如下。

[ERROR] FileNotFoundError: [Errno 2] 没有这样的文件或目录: '/tmp/submission_id' 追溯(最近一次通话): 文件“/var/task/lambda_function.py”,第 24 行,在 lambda_handler 中 client.upload_file('/tmp/submission_id', 'mb-sentiment' , 'data_file')

有人知道我如何准确地编写代码吗?这似乎没有什么困难,但我是一个正在跟上速度的新手。检查了一些其他帖子,但 none 似乎解决了这个特定的用例。

谢谢!

在我看来你应该在最后加上 .txt:

client.upload_file('/tmp/submission_id.txt', 'mb-sentiment' , 'data_file')