简体   繁体   English

Python - 在服务器端解析multipart / form-data请求

[英]Python - Parsing multipart/form-data request on server side

Im trying to do a http 'POST' with multipart/form-data to a python GAE backend. 我试图用multipart / form-data做一个http'POST'到python GAE后端。 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. 谢谢。

For some reason cgi.FieldStorage() wasnt working for me, but only the deprecated method : 由于某种原因,cgi.FieldStorage()不适用于我,但只有弃用的方法:

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

Dont know why but as long as its working im fine with that. 不知道为什么,但只要它的工作即时通讯。

You want the .cgi python library. 你想要.cgi python库。

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", "")

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM