Skip to content

Instantly share code, notes, and snippets.

@mwt
Forked from davidejones/handler_fieldstorage.py
Created January 25, 2021 21:01
Show Gist options
  • Save mwt/6c26738b4b098201734d8b4173f53642 to your computer and use it in GitHub Desktop.
Save mwt/6c26738b4b098201734d8b4173f53642 to your computer and use it in GitHub Desktop.
aws lambda parsing multipart form with python3
from cgi import FieldStorage
from io import BytesIO
def parse_into_field_storage(fp, ctype, clength):
fs = FieldStorage(
fp=fp,
environ={'REQUEST_METHOD': 'POST'},
headers={
'content-type': ctype,
'content-length': clength
},
keep_blank_values=True
)
form = {}
files = {}
for f in fs.list:
if f.filename:
files.setdefault(f.name, []).append(f)
else:
form.setdefault(f.name, []).append(f.value)
return form, files
def handler(event, context):
body_file = BytesIO(bytes(event["body"], "utf-8"))
form, files = parse_into_field_storage(
body_file,
event['headers']['content-type'],
body_file.getbuffer().nbytes
)
print(form)
print(files)
return {
"statusCode": 200,
"body": json.dumps({})
}
from cgi import parse_header, parse_multipart
import json
def handler(event, context):
content_type = event['headers'].get('Content-Type', '') or event['headers'].get('content-type', '')
c_type, c_data = parse_header(content_type)
c_data["boundary"] = bytes(c_data["boundary"], "utf-8")
body_file = BytesIO(bytes(event["body"], "utf-8"))
form_data = parse_multipart(body_file, c_data)
print(form_data)
return {
"statusCode": 200,
"body": json.dumps({})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment