import socket import re import sys import mini_frame # 經過外部傳端口號給套接字 # tcp_port = sys.argv[1] class Mini_Wsgi(object): def __init__(self): self.tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.tcp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # 綁定端口 self.tcp_socket.bind(("", 7780)) # 監聽事件 self.tcp_socket.listen(128) # 定義一個字典保存用戶的請求 self.env = dict() def index(self, user, new_socket): response = "HTTP/1.1 200 ok\r\n" + "content = 'charset=utf-8'" response += "\r\n" try: user_file = "./" + "static" + user with open(user_file, "rb") as f: html_content = f.read() f.close() response += html_content.decode("utf-8") new_socket.send(response.encode("utf-8")) except Exception as ret: return "頁面不存在" def center(self, user, new_socket): response = "HTTP/1.1 200 ok\r\n" + "content = 'charset=utf-8'" response += "\r\n" try: user_file = "./" + "static" + user with open(user_file, "rb") as f: html_content = f.read() f.close() response += html_content.decode("utf-8") new_socket.send(response.encode("utf-8")) except Exception as ret: return "頁面不存在" def start_response(self, s_heard, heards): self.s_heard = s_heard print(heards) h = list() for a in heards: for b in a: h.append(b) print(h) self.heards_all += "%s:%s" % (h[0], h[1]) self.heards_all += ";" print(self.heards_all) def server_run(self): while True: # 等待新用戶的連接,返回一個元組 new_socket, new_addr = self.tcp_socket.accept() browser_date = new_socket.recv(1024) # 對瀏覽器返回的數據進行切片處理 browser_content = browser_date.decode("utf-8").split("\r\n") print(browser_content[0], browser_content) # browser_content = ['GET /你請求的內容 HTTP/1.1', 'Host: 127.0.0.1:7780', 'Connection: keep-alive', 'Cache-Control: max-age=0', 'Upgrade-Insecure-Requests: 1', 'User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0', 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Encoding: gzip, deflate, sdch, br', 'Accept-Language: zh-CN,zh;q=0.8', '', ''] # browser_content[0] = GET /你請求的內容 HTTP/1.1 page_name = re.match(r"[^/]*([/]+.*)[ ].*", browser_content[0]) # 獲得第一條元素,用空格繼續切 # a = browser_content[0].split(" ") # 獲得用戶請求的數據內容 user = page_name.group(1) print(user) self.env["PATH_INFO"] = user # 判斷用戶請求的數據以什麼結尾,範圍什麼頁面 # if user.endswith(".html"): # # 調用相對應頁面的函數 # if user == "/center.html": # self.center(user, new_socket) # else: # self.index(user, new_socket) if user.endswith(".html"): # 調用框架,返回動態數據 html = mini_frame.application(self.env, self.start_response) print(html) print(str(self.heards_all)) response = "HTTP/1.1 " + self.s_heard + "\r\n" + self.heards_all + "\r\n" response += "\r\n" response += html new_socket.send(response.encode("utf-8")) print("------") # 若是用戶不是.html結尾,則給他加上.html,返回給用戶主頁 else: response = "HTTP/1.1 200 ok\r\n" + "content = 'charset=utf-8'" response += "\r\n" # 發送body f = open("./static/index.html", "rb") html_content = f.read() f.close() response += html_content.decode("utf-8") new_socket.send(response.encode("utf-8")) new_socket.close() # self.tcp_socket.close() def main(): server_web = Mini_Wsgi() server_web.server_run() server_web.tcp_socket.close() if __name__ == '__main__': main()
下面是mini_frame的代碼:html
import pymysql
info_path = dict() # 定義一個路由函數用來裝飾下面函數 def route(file_name): def set_func(func): info_path[file_name] = func def call_func(*args, **kwargs): return func(*args, **kwargs) return call_func return set_func @route("/center.html") def center(): # user_file = "./" + "static" + user # with open("./static/center.html", "rb") as f: # html_content = f.read() html_content = "" # # 創建數據庫的連接 conn = pymysql.connect(host="127.0.0.1", user="root", password="0626",database="python_1", charset="utf8") # 創建遊標對象 cursor = conn.cursor() # 執行sql語句 cursor.execute("select * from student;") # 獲取查詢的數據 vulue = cursor.fetchall() # 關閉遊標對象 cursor.close() # 關閉數據庫連接 conn.close() people_msg = "序號:%s 名字:%s 出生年月:%s 性別:%s" for date in vulue: html_content += people_msg % (date[0], date[1], date[2], date[3]) html_content += "\t\n" # print(html_content) # html_content += vulue return html_content @route("/index.html") def register(): with open("./static/index.html", "rb") as f: html_content = f.read() return html_content # env = {"center.py":center, # "register.py":register} def application(env, start_response): start_response("200 ok", [("content-type","text/html;charset=utf-8"),]) try: file_name = env["PATH_INFO"] print(file_name) return info_path[file_name]() except Exception as ret: return "404 error"
這個程序有個問題就是,我一直開着,瀏覽器請求過來後,能正常顯示出數據,可是等待一會後下面這行代碼報錯:python
# 獲得用戶請求的數據內容 user = page_name.group(1)
說取不出來值,可若是沒有請求過來的話accept默認不是堵塞的嗎,爲何還能執行到正則匹配用戶請求的值這行代碼?(以前用的字符串切割取值,報錯,換成正則也是報錯,實在是想不明白accept接受到什麼請求了打印出來的是個空的,/ 都沒有)mysql
如今正惡補下Flask與Django框架。web