python3 搭建简单的web服务器

假设目标机器上已经配置好python3。

创建文件server.py,内容如下。

from http.server import HTTPServer, BaseHTTPRequestHandler
import json

data = {'err':0, 'msg': 'OK'}
host = ('localhost', 8080)

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("Server is started! Listening at http://%s:%s" % host)
    server.serve_forever()

在当前目录执行 python server.py

Starting server, listening: http://localhost:8080

浏览器中访问 http://localhost:8080,得到返回结果

{"err": 0, "msg": "OK"}

同时web服务器会打印日志

Starting server, listening: http://localhost:8080
127.0.0.1 - - [27/Apr/2019 21:26:51] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [27/Apr/2019 21:26:51] "GET /favicon.ico HTTP/1.1" 200 -

如果需要部署到服务器,需要移除localhost。

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

data = {'err':0, 'msg': 'OK'}
host = ('', 8080)

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__':
    pid = os.fork()
    if pid != 0:
        os._exit(0)
    else:
        server = HTTPServer(host, Resquest)
        print("Server is started! Listening at http://%s:%s" % host)
        server.serve_forever()

你可能感兴趣的:(python3 搭建简单的web服务器)