Python3 http.server POST示例

Tei*_*ion 21 python python-3.x

我正在将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]);
Run Code Online (Sandbox Code Playgroud)

Tei*_*ion 18

在戳了几个小时的谷歌后,我发现了以下工作.

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"))
Run Code Online (Sandbox Code Playgroud)

我很惊讶这是多么容易.