Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read form-data with AWS python lambda

I want to read the "key" parameter of a http post request but it is not working.

def my_handler(event, context):
    print(event)
    print(event['body'])
    print("key: " + event['key'])

    key = event['query']['key']

    encoded_string = str(key).encode("utf-8")
    # Create the file named for example "42.json" containing the appropriate data
    s3_path =  str(key) + '.json'
    s3 = boto3.resource("s3")
    s3.Bucket(BUCKET_NAME).put_object(Key=s3_path, Body=encoded_string)

    message = {
       'message': 'Created {}!'.format(key)  
    }
    return {
        'statusCode': 200,
        'headers': {'Content-Type': 'application/json'},
        'body': json.dumps(message)
    }

Update: If I use the code below, I can read JSON data in an http post but I still cannot read form-data.

def my_handler(event, context):
    print(event)
    print(event['body'])
   # print("key: " + event['key'])
    print("key  " + json.loads(event['body'])["key"])

    key = json.loads(event['body'])["key"]

    encoded_string = str(key).encode("utf-8")
    # Create the file named for example "42.json" containing the appropriate data
    s3_path =  str(key) + '.json'
    s3 = boto3.resource("s3")
    s3.Bucket(BUCKET_NAME).put_object(Key=s3_path, Body=encoded_string)

    message = {
       'message': 'Created {}!'.format(key)  
    }
    return {
        'statusCode': 200,
        'headers': {'Content-Type': 'application/json'},
        'body': json.dumps(message)
    }
like image 241
Niklas Rosencrantz Avatar asked Feb 18 '26 01:02

Niklas Rosencrantz


1 Answers

I had trouble with this too. I'm specifically working on an AWS Lambda using python3.7. Took a day, but I figured it out.

This code parses the "multipart/form-data" body into a dict called form_data. There are two notes: (a) This code makes an assumption that the post body and headers are utf-8 encoded; that seems to be particular to the AWS API Gateway, but I didn't do any due diligence to test that this holds for all cases. (b) Because the form could have multiple values for any field, the value for any key is a list. You were asking about retrieving "key" from the form data. If there's a single value for "key" then you'd reference form_data['key'][0].

import cgi
import io

def handler(event, context):
    print(event)
    print(event['body'])

    fp = io.BytesIO(event['body'].encode('utf-8'))
    pdict = cgi.parse_header(event['headers']['Content-Type'])[1]
    if 'boundary' in pdict:
        pdict['boundary'] = pdict['boundary'].encode('utf-8')
    pdict['CONTENT-LENGTH'] = len(event['body'])
    form_data = cgi.parse_multipart(fp, pdict)
    print('form_data=', form_data)
like image 174
bonafidejed Avatar answered Feb 20 '26 22:02

bonafidejed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!