【问题标题】:Message: Unsupported method ('POST'). Error 501 Python消息:不支持的方法('POST')。错误 501 蟒蛇
【发布时间】:2019-05-05 19:14:25
【问题描述】:

我正在尝试在 udacity 在线学院学习一些 Http Server。问题是以下代码触发了错误消息:不支持的方法('POST')。错误 501 Python:

from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import parse_qs


class MessageHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        # 1. How long was the message?
        length = int(self.headers.get('Content-length', 0))

        # 2. Read the correct amount of data from the request.
        data = self.rfile.read(length).decode()

        # 3. Extract the "message" field from the request data.
        message = parse_qs(data)["message"][0]

        # Send the "message" field back as the response.
        self.send_response(200)
        self.send_header('Content-type', 'text/plain; charset=utf-8')
        self.end_headers()
        self.wfile.write(message.encode())


if __name__ == '__main__':
    server_address = ('', 8000)
    httpd = HTTPServer(server_address, MessageHandler)
    httpd.serve_forever()

【问题讨论】:

    标签: python-3.x http post server


    【解决方案1】:

    哪个Python?你的代码是正确的。立即测试,它发送响应。

    我所做的唯一修改是

    #message = parse_qs(data)["message"][0]
    message = 'hello'
    

    客户端代码:

    import requests
    res = requests.post('http://localhost:8000/abc', data = {'key':'value'})
    print(res)
    

    客户端得到200响应

    【讨论】:

    • 您能否在答案中添加更多信息。我是一个菜鸟,如果有整个代码知道我在哪里失败了,我会很酷
    • 事实是您的代码是正确。我刚刚发布了一个 client 代码示例,以显示我是如何测试您的服务器的。这一切都奏效了
    • 非常感谢葡萄 :-) 但是为什么不工作,我总是得到这个 501 错误而没有显示我在 HTML 中编写的内容?
    • 你能告诉我你是如何测试你的服务器的吗?你的客户是什么?
    • 非常感谢您对我的耐心等待。我正在做的只是在我的 git bash 终端中编写“python -m http.server”。我有一个带有文本字段的 HTML 文件,当您按发送时,应该在对提到的 python 代码执行请求后向我显示此文本。我做错了吗?
    猜你喜欢
    • 2021-06-17
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 2019-07-28
    • 2016-05-04
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    相关资源
    最近更新 更多