废话不多说,先上代码
运行环境为python2.7,python3的在文章底部
#!usr/bin/python
# encoding:utf-8
import BaseHTTPServer as hs
import os
class ServerException(Exception):
pass
class RequestHandler(hs.BaseHTTPRequestHandler):
def send_content(self, page, status=200):
self.send_response(status)
self.send_header("Content-type", "text/html")
self.send_header("Content-Length", str(len(page)))
self.end_headers()
self.wfile.write(page)
# print(page)
def send_css(self, page, status=200):
self.send_response(status)
self.send_header("Content-type", "text/css")
self.send_header("Content-Length", str(len(page)))
self.end_headers()
self.wfile.write(page)
def send_png(self, page, status=200):
self.send_response(status)
self.send_header("Content-type", "image/png")
self.send_header("Content-Length", str(len(page)))
self.end_headers()
self.wfile.write(page)
def do_GET(self):
try:
full_path = os.getcwd() + self.path
# print full_path
# os.startfile(full_path)
# path is correct
if not os.path.exists(full_path):
raise ServerException("'{0}' not found".format(self.path))
elif os.path.isfile(full_path):
self.handle_file(full_path)
else:
raise ServerException("Unknown object '{0}'".format(self.path))
except Exception as ms