charlie
charlie

Reputation: 3

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

I am trying to create a new file using Python in AWS Lambda and write to it and then upload to an S3 bucket. I want each filename to be unique based on a variable. In this instance it's submission_id.

import json
import sys
import logging
import boto3

client = boto3.client('s3')

Parse the data from webhook API call (This all works fine)

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

Create new file with results and upload to S3.

Want to use submission_id as filename variable.

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

Upload the file to S3 bucket

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

The error I am receiving is as follows.

[ERROR] FileNotFoundError: [Errno 2] No such file or directory: '/tmp/submission_id' Traceback (most recent call last):   File "/var/task/lambda_function.py", line 24, in lambda_handler     client.upload_file('/tmp/submission_id', 'mb-sentiment' , 'data_file')

Does anyone have any idea on how I can accurately code this? This does not seem to be anything difficult, but I am a newbie getting up to speed. Checked some other posts but none seem to address this particular use case.

Thanks!

Upvotes: 0

Views: 6017

Answers (1)

Marcin
Marcin

Reputation: 238061

Seems to me that you should have .txt at the end:

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

Upvotes: 1

Related Questions