python Python3 http.server POST 示例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2121481/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python3 http.server POST example
提问by Teifion
I'm converting a Python2.6 app into a Python3 app and I'm getting stuck with the server. I've managed to get it serving up GET requests just fine but POST continues to elude me. Here is what I started with in 2.6 that worked but in 3.x the normal server does not handle POST requests. From my reading of the Python manual it appears that I must use a CGI server class instead and also map the scripts to that directory. I'd rather not have to do this but I cannot find another way. Am I missing something?
我正在将 Python2.6 应用程序转换为 Python3 应用程序,但我在服务器上遇到了问题。我已经设法让它很好地提供 GET 请求,但 POST 继续躲避我。这是我在 2.6 中开始的工作,但在 3.x 中,普通服务器不处理 POST 请求。从我对 Python 手册的阅读看来,我必须改用 CGI 服务器类并将脚本映射到该目录。我宁愿不必这样做,但我找不到其他方法。我错过了什么吗?
def do_POST(self):
ctype, pdict = cgi.parse_header(self.headers.get('content-type'))
if ctype == 'multipart/form-data':
query = cgi.parse_multipart(self.rfile, pdict)
self.send_response(301)
self.end_headers()
upfilecontent = query.get('upfile')
print("filecontent", upfilecontent[0])
self.wfile.write("<HTML>POST OK.<BR><BR>");
self.wfile.write(upfilecontent[0]);
回答by Teifion
After poking and a few more hours of googling I've found the following works.
经过戳和几个小时的谷歌搜索后,我发现了以下作品。
def do_POST(self):
length = int(self.headers['Content-Length'])
post_data = urllib.parse.parse_qs(self.rfile.read(length).decode('utf-8'))
# You now have a dictionary of the post data
self.wfile.write("Lorem Ipsum".encode("utf-8"))
I'm surprised at how easy this was.
我很惊讶这是多么容易。