【问题标题】:Python3 http.server POST examplePython3 http.server POST 示例
【发布时间】:2010-01-23 00:29:38
【问题描述】:

我正在将 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]);

【问题讨论】:

  • 普通服务器在 Python 3 中处理 post 请求的方式与在 Python 2 中的处理方式不同吗?你能解释一下问题是什么吗?
  • 是的,它不会隐含 do_post() 函数,而 Python2 中的函数会。 Python 文档中没有关于如何克服它的可靠代码示例,谷歌搜索也没有帮助。

标签: python python-3.x


【解决方案1】:

在戳了戳和几个小时的谷歌搜索之后,我发现了以下作品。

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

我很惊讶这是多么容易。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-29
    • 1970-01-01
    • 2018-07-11
    相关资源
    最近更新 更多