python BaseHTTPRequestHandler返回json坏字符串

时间:2018-03-16 18:33:43

标签: python python-3.x http get

我有一个简单的http服务器,如下所示:

from http.server import BaseHTTPRequestHandler, HTTPServer


class S(BaseHTTPRequestHandler):
    def _set_headers(self):
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()

    def do_GET(self):
        self._set_headers()
        self.wfile.write(bytes("{\"result\": 200}", "utf-8"))

    def do_HEAD(self):
        self._set_headers()

    def do_POST(self):
        # Doesn't do anything with posted data
        self._set_headers()
        self.wfile.write(bytes("{\"result\": 200}", "utf-8"))


def run(server_class=HTTPServer, handler_class=S, port=8000):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print("Starting http server on port " + str(port))
    httpd.serve_forever()


if __name__ == "__main__":
    from sys import argv

    if len(argv) == 2:
        run(port=int(argv[1]))
    else:
        run()

当我发出GET请求时,我希望json:{result: 200},但我得到bad string。我该怎么做才能解决这个问题?我已经看过其他例子,你可以把你的python对象写成json,但不确定如何把它放到这段代码中。

0 个答案:

没有答案