我正试图在一个大胆的在线学院中学习一些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()
答案 0 :(得分: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
响应