–主程序
import socket
import multiprocessing
import re
import frame_web
class MiniServer(object):
print("MiniServer正在运行...")
def __init__(self):
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server_socket.bind(("", 9999))
self.server_socket.listen(128)
def mini_server(self, new_socket):
request = new_socket.recv(1024*1024).decode("utf-8")
request_lines = request.splitlines()
'''['GET / HTTP/1.1', 'Host: 127.0.0.1:9999', 'Connection: keep-alive',
'Cache-Control: max-age=0', 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36',
'Upgrade-Insecure-Requests: 1',
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Encoding: gzip, deflate, br', 'Accept-Language: zh-CN,zh;q=0.9', '']'''
ret = re.match(r"[^/]*(/[^ ]*).*", request_lines[0])
if ret:
file_name = ret.group(1)
if file_name == "/":
file_name = "/index.html"
if not file_name.endswith(".py"):
response = "HTTP/1.1 200 OK\r\n"
# response += "Content-Type: text/html; charset=utf-8\r\n"
response += "\r\n"
try:
with open(("./static"+ file_name), "rb") as f:
content = f.read()
except Exception:
response = "HTTP/1.1 404 NOT FOUND\r\n"
response += "\r\n"
response += "ERR_EMPTY_FILE"
new_socket.send(response.encode("utf-8"))
else:
new_socket.send(response.encode("utf-8"))
new_socket.send(content)
else:
env = dict()
env["file_path"] = file_name
body = frame_web.application(env, self.set_response)
headers = "HTTP/1.1 %s\r\n" %self.status
for i in self.header:
headers += "%s:%s\r\n"% (i[0], i[1])
headers += "\r\n"
new_socket.send((headers + body).encode("utf-8"))
def set_response(self, status, header):
self.status = status
self.header = header
def run(self):
while True:
new_socket, new_addr = self.server_socket.accept()
p = multiprocessing.Process(target=self.mini_server, args=(new_socket,))
p.start()
new_socket.close()
self.server_socket.close()
def main():
server = MiniServer()
server.run()
if __name__ == "__main__":
main()
–框架
def index():
with open("./templates/index.html") as f:
return f.read()
def center():
with open("./templates/center.html") as f:
return f.read()
def application(evn, set_response):
set_response("200 OK",[("Content-Type", "text/html;charset=utf-8")])
file_name = evn["file_path"]
if file_name == "/index.py":
return index()
elif file_name == "/center.py":
return center()
else:
return "55555555555555"