python3 使用http.server模块 搭建一个简易的http服务器

 

from http.server import HTTPServer, BaseHTTPRequestHandler
import json

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())

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

 

启动服务,在控制台看到:

 

在浏览器输入http://localhost:8888/进行访问:

 

此时查看控制台能看到log已经打印了请求:

 

posted @ 2018-01-19 17:35  参与商  阅读(38027)  评论(0编辑  收藏  举报