7

I am decoding form fields submitted via a HTTP POST request using request-toolbelt. I successfully instantiated a MultipartDecoder like described here. Now I would like to access the form fields by the name I have given them when sending the request.

I am able to get the name of a field like this

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"
decoder = decoder.MultipartDecoder(multipart_string, content_type)
field_name = decoder.parts[0].headers[b'Content-Disposition'].decode().split(';')[1].split('=')[1]

But this seems quite wrong. What is the usual way to access the form field names?

joleroi
  • 181
  • 2
  • 7

1 Answers1

4

I use it in the following to decode the result of that method:

    lst = []
for part in decoder.MultipartDecoder(postdata.encode('utf-8'), content_type_header).parts:
    disposition = part.headers[b'Content-Disposition']
    params = {}
    for dispPart in str(disposition).split(';'):
        kv = dispPart.split('=', 2)
        params[str(kv[0]).strip()] = str(kv[1]).strip('\"\'\t \r\n') if len(kv)>1 else str(kv[0]).strip()
    type = part.headers[b'Content-Type'] if b'Content-Type' in part.headers else None
    lst.append({'content': part.content, "type": type, "params": params})

I assume because its a standard Mime header, there are functions that can do the same, but with less code as well.