Python http服务器示例代码:
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 30 19:29:13 2018
@author: einsn
"""
from http.server import BaseHTTPRequestHandler, HTTPServer
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
try:
f = open(self.path[1:], 'rb')
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(f.read())
f.close()
except IOError:
self.send_error(404, 'File Not Found: %s' % self.path)
def do_POST(self):
print("get post:")
print(self.path)
def main():
try:
s = HTTPServer(('', 8000), MyHandler)
print('Welcome to the machine...', end='')
print('Press CTRL+C once or twice to quit')
s.serve_forever()
except KeyboardInterrupt:
print('^C received, shutting down server')
s.socket.close()
if __name__ == '__main__':
main()
打开浏览器,访问 http://localhost:8000, 或者使用curl 获取页面。