【问题标题】:Creating a new file, writing to it and uploading to S3 using Python in Lambda在 Lambda 中使用 Python 创建新文件、写入文件并上传到 S3
【发布时间】:2020-08-07 11:44:40
【问题描述】:

我正在尝试在 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')

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

谢谢!

【问题讨论】:

  • data_file = open('/tmp/' + submit_id + '.txt', 'w+')

标签: python amazon-web-services amazon-s3 aws-lambda upload


【解决方案1】:

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

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

【讨论】:

  • 感谢您指出 Marcin。因此,我进行了更改,使我克服了该错误并将文件发送到 S3。但是文件名一直使用“data_file”名称。所以我更新了它,现在一切正常。这是更新后的工作代码:client.upload_file('/tmp/submission_id.txt', 'mb-sentiment', submit_id + '.txt')
  • @charlie 很高兴听到。那么猜猜它现在工作了吗?如果是这样,我们将不胜感激。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多