使用 Python 搭建简易HTTP服务器
from http.server import HTTPServer, BaseHTTPRequestHandler
class Request(BaseHTTPRequestHandler):
def do_GET(self):
# print(self.path)
# self.path 细分
self.send_response(200)
self.send_header('Content-type', 'text/html; charset=utf-8')
self.end_headers()
with open("index.html") as f:
self.wfile.write(f.read().encode()) # wfile = write-file
def do_POST(self):
self.send_response(200)
self.send_header('Content-type', 'text/html; charset=utf-8')
self.end_headers()
self.wfile.write("post".encode())
def run():
host = 'localhost'
port = 80
server = HTTPServer((host, port), Request)
server.serve_forever()
if __name__ == '__main__':
# print(Request.path)
run()
参考
沉舟侧畔千帆过,病树前头万木春。