├── web_server.py ├── web │ └── my_web.py └── html └── index.html .....
import time def application(environ, start_response): status = '200 OK' response_headers = [('Content-Type', 'text/html')] start_response(status, response_headers) return str(environ) + '==Hello world from a simple WSGI application!--->%s\n' % time.ctime()
import select import time import socket import sys import re import multiprocessing class WSGIServer(object): """定義一個WSGI服務器的類""" def __init__(self, port, documents_root, app): # 1. 建立套接字 self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 2. 綁定本地信息 self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.server_socket.bind(("", port)) # 3. 變爲監聽套接字 self.server_socket.listen(128) # 設定資源文件的路徑 self.documents_root = documents_root # 設定web框架能夠調用的函數(對象) self.app = app def run_forever(self): """運行服務器""" # 等待對方連接 while True: new_socket, new_addr = self.server_socket.accept() # 建立一個新的進程來完成這個客戶端的請求任務 new_socket.settimeout(3) # 3s new_process = multiprocessing.Process(target=self.deal_with_request, args=(new_socket,)) new_process.start() new_socket.close() def deal_with_request(self, client_socket): """以長連接的方式,爲這個瀏覽器服務器""" while True: try: request = client_socket.recv(1024).decode("utf-8") except Exception as ret: print("========>", ret) client_socket.close() return # 判斷瀏覽器是否關閉 if not request: client_socket.close() return request_lines = request.splitlines() for i, line in enumerate(request_lines): print(i, line) # 提取請求的文件(index.html) # GET /a/b/c/d/e/index.html HTTP/1.1 ret = re.match(r"([^/]*)([^ ]+)", request_lines[0]) if ret: print("正則提取數據:", ret.group(1)) print("正則提取數據:", ret.group(2)) file_name = ret.group(2) if file_name == "/": file_name = "/index.html" # 若是不是以py結尾的文件,認爲是普通的文件 if not file_name.endswith(".py"): # 讀取文件數據 try: f = open(self.documents_root+file_name, "rb") except: response_body = "file not found, 請輸入正確的url" response_header = "HTTP/1.1 404 not found\r\n" response_header += "Content-Type: text/html; charset=utf-8\r\n" response_header += "Content-Length: %d\r\n" % (len(response_body)) response_header += "\r\n" response = response_header + response_body # 將header返回給瀏覽器 client_socket.send(response.encode('utf-8')) else: content = f.read() f.close() response_body = content response_header = "HTTP/1.1 200 OK\r\n" response_header += "Content-Length: %d\r\n" % (len(response_body)) response_header += "\r\n" # 將header返回給瀏覽器 client_socket.send(response_header.encode('utf-8') + response_body) # 以.py結尾的文件,就認爲是瀏覽須要動態的頁面 else: # 準備一個字典,裏面存放須要傳遞給web框架的數據 env = {} # 存web返回的數據 response_body = self.app(env, self.set_response_headers) # 合併header和body response_header = "HTTP/1.1 {status}\r\n".format(status=self.headers[0]) response_header += "Content-Type: text/html; charset=utf-8\r\n" response_header += "Content-Length: %d\r\n" % len(response_body) for temp_head in self.headers[1]: response_header += "{0}:{1}\r\n".format(*temp_head) response = response_header + "\r\n" response += response_body client_socket.send(response.encode('utf-8')) def set_response_headers(self, status, headers): """這個方法,會在 web框架中被默認調用""" response_header_default = [ ("Data", time.ctime()), ("Server", "ItCast-python mini web server") ] # 將狀態碼/相應頭信息存儲起來 # [字符串, [xxxxx, xxx2]] self.headers = [status, response_header_default + headers] # 設置靜態資源訪問的路徑 g_static_document_root = "./html" # 設置動態資源訪問的路徑 g_dynamic_document_root = "./web" def main(): """控制web服務器總體""" # python3 xxxx.py 7890 if len(sys.argv) == 3: # 獲取web服務器的port port = sys.argv[1] if port.isdigit(): port = int(port) # 獲取web服務器須要動態資源時,訪問的web框架名字 web_frame_module_app_name = sys.argv[2] else: print("運行方式如: python3 xxx.py 7890 my_web_frame_name:application") return print("http服務器使用的port:%s" % port) # 將動態路徑即存放py文件的路徑,添加到path中,這樣python就可以找到這個路徑了 sys.path.append(g_dynamic_document_root) ret = re.match(r"([^:]*):(.*)", web_frame_module_app_name) if ret: # 獲取模塊名 web_frame_module_name = ret.group(1) # 獲取能夠調用web框架的應用名稱 app_name = ret.group(2) # 導入web框架的主模塊 web_frame_module = __import__(web_frame_module_name) # 獲取那個能夠直接調用的函數(對象) app = getattr(web_frame_module, app_name) # print(app) # for test # 啓動http服務器 http_server = WSGIServer(port, g_static_document_root, app) # 運行http服務器 http_server.run_forever() if __name__ == "__main__": main()
python3 web_server.py my_web:application