1.使用類
import socket
import re
from multiprocessing import Process
#設(shè)置靜態(tài)文件根目錄
HTML_ROOT_DIR = "./html"
class HTTPServer(object):
""""""
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)
def start(self):
self.server_socket.listen(128)
while True:
client_socket, client_address = self.server_socket.accept()
# print("[%s, %s]用戶連接上了" % (client_address[0],client_address[1]))
print("[%s, %s]用戶連接上了" % client_address)
handle_client_process = Process(target=self.handle_client, args=(client_socket,))
handle_client_process.start()
client_socket.close()
def handle_client(self, client_socket):
"""處理客戶端請求"""
#獲取客戶端請求數(shù)據(jù)
request_data = client_socket.recv(1024)
print("request data:", request_data)
request_lines = request_data.splitlines()
for line in request_lines:
print(line)
#解析請求報文
# 'GET / HTTP/1.1'
request_start_line = request_lines[0]
#提取用戶請求的文件名
print("*" * 10)
print(request_start_line.decode("utf-8"))
file_name = re.match(r"\w+ +(/[^ ]*) ", request_start_line.decode("utf-8")).group(1)
if "/" == file_name:
file_name = "/index.html"
#打開文件,讀取內(nèi)容
try:
file = None
file = open(HTML_ROOT_DIR + file_name, "rb")
file_data = file.read()
#構(gòu)造響應(yīng)數(shù)據(jù)
response_start_line = "HTTP/1.1 200 OK\r\n"
response_headers = "Server: My server\r\n"
response_body = file_data.decode("utf-8")
except FileNotFoundError:
response_start_line = "HTTP/1.1 404 Not Found\r\n"
response_headers = "Server: My server\r\n"
response_body = "The file is not found!"
finally:
if file and (not file.closed):
file.close()
response = response_start_line + response_headers + "\r\n" + response_body
print("response data:", response)
#向客戶端返回響應(yīng)數(shù)據(jù)
client_socket.send(bytes(response, "utf-8"))
#關(guān)閉客戶端連接
client_socket.close()
def bind(self, port):
self.server_socket.bind(("", port))
def main():
http_server = HTTPServer()
# http_server.set_port
http_server.bind(8000)
http_server.start()
if __name__ == "__main__":
main()
2. ?web 服務(wù)器動態(tài)資源請求
2.1 瀏覽器請求動態(tài)頁面過程

2.2WSGI
怎么在你剛建立的Web服務(wù)器上運行一個Django應(yīng)用和Flask應(yīng)用,如何不做任何改變而適應(yīng)不同的web架構(gòu)呢?
在以前,選擇Python web架構(gòu)會受制于可用的web服務(wù)器,反之亦然。如果架構(gòu)和服務(wù)器可以協(xié)同工作,那就好了:

但有可能面對(或者曾有過)下面的問題,當要把一個服務(wù)器和一個架構(gòu)結(jié)合起來時,卻發(fā)現(xiàn)他們不是被設(shè)計成協(xié)同工作的:

那么,怎么可以不修改服務(wù)器和架構(gòu)代碼而確??梢栽诙鄠€架構(gòu)下運行web服務(wù)器呢?答案就是Python Web Server Gateway Interface (或簡稱WSGI,讀作“wizgy”)。

WSGI允許開發(fā)者將選擇web框架和web服務(wù)器分開。可以混合匹配web服務(wù)器和web框架,選擇一個適合的配對。比如,可以在Gunicorn或者Nginx/uWSGI或者Waitress上運行Django, Flask,或Pyramid。真正的混合匹配,得益于WSGI同時支持服務(wù)器和架構(gòu):
