Parse multipart request string in Python

前端 未结 5 1622
走了就别回头了
走了就别回头了 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:06

    Expanding on sam-anthony' answer (I had to make some fixes for it to work on python 3.6.8):

    from requests_toolbelt.multipart import decoder
    
    multipart_string = b"--ce560532019a77d83195f9e9873e16a1\r\nContent-Disposition: form-data; name=\"author\"\r\n\r\nJohn Smith\r\n--ce560532019a77d83195f9e9873e16a1\r\nContent-Disposition: form-data; name=\"file\"; filename=\"example2.txt\"\r\nContent-Type: text/plain\r\nExpires: 0\r\n\r\nHello World\r\n--ce560532019a77d83195f9e9873e16a1--\r\n"
    content_type = "multipart/form-data; boundary=ce560532019a77d83195f9e9873e16a1"
    
    for part in decoder.MultipartDecoder(multipart_string, content_type).parts:
      print(part.text)
    
    John Smith
    Hello World
    

    What you'd have to do is install this library through pip install requests-toolbelt --target=. and then upload it along with your lambda script

    Here's a working example:

    from requests_toolbelt.multipart import decoder
    
    def lambda_handler(event, context):
    
        content_type_header = event['headers']['Content-Type']
    
        body = event["body"].encode()
    
        response = ''
        for part in decoder.MultipartDecoder(body, content_type_header).parts:
          response += part.text + "\n"
    
        return {
            'statusCode': 200,
            'body': response
        }
    

    This should be enough for your dependencies to be recognized. If they aren't, try using the "/python/lib/python3.6/site-packages" file structure inside the zip with your python script at root"

提交回复
热议问题