Parse multipart request string in Python

前端 未结 5 1623
走了就别回头了
走了就别回头了 2020-12-10 09:15

I have a string like this

\"--5b34210d81fb44c5a0fdc1a1e5ce42c3\\r\\nContent-Disposition: form-data; name=\\\"author\\\"\\r\\n\\r\\nJohn Smith\\r\\n--5b34210d         


        
5条回答
  •  忘掉有多难
    2020-12-10 10:04

    If you want to use Python's CGI,

    from cgi import parse_multipart, parse_header
    from io import BytesIO
    
    c_type, c_data = parse_header(event['headers']['Content-Type'])
    assert c_type == 'multipart/form-data'
    decoded_string = base64.b64decode(event['body'])
    #For Python 3: these two lines of bugfixing are mandatory
    #see also: https://stackoverflow.com/questions/31486618/cgi-parse-multipart-function-throws-typeerror-in-python-3
    c_data['boundary'] = bytes(c_data['boundary'], "utf-8")
    c_data['CONTENT-LENGTH'] = event['headers']['Content-length']
    form_data = parse_multipart(BytesIO(decoded_string), c_data)
    
    for image_str in form_data['file']:
        ...
    

提交回复
热议问题