下面的代码是一个简单的http服务示例,并重载了log_message函数,可以在里面自定义日志输出。

from http.server import HTTPServer, BaseHTTPRequestHandler
import json
import sys

data = {'result': 'this is a test'}
host = ('localhost', 8888)

class Resquest(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        self.wfile.write(json.dumps(data).encode())

    def log_message(self, format, *args):
       sys.stderr.write("logs : ")
       BaseHTTPRequestHandler.log_message(self, format, *args)

if __name__ == '__main__':
    server = HTTPServer(host, Resquest)
    print("Starting server, listen at: %s:%s" % host)
    server.serve_forever()
下一篇