Python - Parsing multipart/form-data request on server side

十年热恋 提交于 2019-12-22 04:58:11

问题


Im trying to do a http 'POST' with multipart/form-data to a python GAE backend. My server side method is receiving the complete body but i have absolutely no idea how to parse the body content without going over it manually and splitting the text for values.

My request looks like this:

POST /android/v4/MyPostMethod HTTP/1.1
Accept: */*
Accept-Charset: *
Content-Length: 186808
Content-Type: multipart/form-data; boundary=*****; charset="utf-8"
Content_Length: 186808
Content_Type: multipart/form-data; boundary=*****
Host: myhost.appspot.com
User-Agent: Dalvik/1.6.0 (Linux; U; Android 4.1.2; GT-I9300 Build/XXXXX)
Via: HTTP/1.1 MSP-YV

--*****
Content-Disposition: form-data; name="value1"
Content-Type: text/plain; charset=UTF-8

f0ef73c5-54dd-40cf-9ee7-5c4cb764eb28
--*****
Content-Disposition: form-data; name="value2"
Content-Type: text/plain; charset=UTF-8

10d71e73-4d4d-4607-b271-f7efcfd0c59d
--*****
Content-Disposition: form-data; name="value3"
Content-Type: text/plain; charset=UTF-8

10d71e73-4d4d-4607-b271-f7efdfdfdfdf
--*****
Content-Disposition: form-data; name="logText"; filename="log.txt"
Content-Type: text/plain
Content-Transfer-Encoding: binary

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
...
--*****--

I've searched around and couldn't find a good explanation of how to do this trivial thing. Appreciate if someone could help me here. Thanks.


回答1:


For some reason cgi.FieldStorage() wasnt working for me, but only the deprecated method :

pdict = {'boundary':'*****'}
cgi.parse_multipart(self.request.body_file, pdict)

Dont know why but as long as its working im fine with that.




回答2:


You want the .cgi python library.

Specifically something like this:

import cgi
form = cgi.FieldStorage() 
value1 = form.getfirst("value1", "")
value2 = form.getfirst("value2", "") 
value3 = form.getfirst("value3", "") 
logtext = form.getfirst("logText", "")



回答3:


If you want the uploaded files, you can do this

for upload in self.get_uploads():

If you want just a text field:

x = self.request.get('value1')



来源:https://stackoverflow.com/questions/25645253/python-parsing-multipart-form-data-request-on-server-side

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!