我正在尝试编写一个简单的“服务器”,它继承自BaseHTTPRequestHandler
并能够接收 GET 和 POST 请求。我有一个server.py
文件,到目前为止,看起来像这样:
from http.server import BaseHTTPRequestHandler, HTTPServer
from cgi import parse_header, parse_multipart
from urllib.parse import parse_qs
host = "localhost"
port = 8080
hello_msg = "Server running..."
class Server(BaseHTTPRequestHandler):
def _set_headers(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_GET(self):
self.respond_OK(hello_msg)
def do_POST(self):
print("Post")
data = self.parse_POST()
print(data)
print(type(data))
self.respond_OK("End post")
def parse_POST(self):
ctype, pdict = parse_header(self.headers['content-type'])
if ctype == 'multipart/form-data':
postvars = parse_multipart(self.rfile, pdict)
elif ctype == 'application/x-www-form-urlencoded':
length = int(self.headers['content-length'])
postvars = parse_qs(
self.rfile.read(length),
keep_blank_values=1)
else:
postvars = {}
return postvars
def respond_OK(self, msg):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(bytes(msg, "utf-8"))
if __name__ == "__main__":
webServer = HTTPServer((host, port), Server)
print("Server started http://%s:%s" % (host, port))
try:
webServer.serve_forever()
except KeyboardInterrupt:
pass
webServer.server_close()
print("Server stopped.")
还有一个client.py
看起来像这样的文件:
import requests
sample = {
"msg": "sample post message",
"number": 159687,
"list": ["one", "two", "three"]
}
url = "http://localhost:8080"
r = requests.post(url, sample)
在do_POST
函数中,我希望data
变量与客户端发送的变量完全相同sample
,但我最终得到的是:
{b'msg': [b'sample post message'], b'number': [b'159687'], b'list': [b'one', b'two', b'three']}
如您所见,它是一个字典,但键和值是字节而不是字符串。我可以在解析后简单地转换键和值,但我的印象是我做错了什么,并且解析的结果应该已经是字符串而不是字节。
我究竟做错了什么?这里的解决方案是简单地添加另一个将字节转换为字符串的步骤吗?