1.使用類
import socket
import re
from multiprocessing import Process
#設置靜態文件根目錄
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):
"""處理客戶端請求"""
#獲取客戶端請求數據
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"
#打開文件,讀取內容
try:
file = None
file = open(HTML_ROOT_DIR + file_name, "rb")
file_data = file.read()
#構造響應數據
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)
#向客戶端返回響應數據
client_socket.send(bytes(response, "utf-8"))
#關閉客戶端連接
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 服務器動態資源請求
2.1 瀏覽器請求動態頁面過程
2.2WSGI
怎么在你剛建立的Web服務器上運行一個Django應用和Flask應用,如何不做任何改變而適應不同的web架構呢?
在以前,選擇Python web架構會受制于可用的web服務器,反之亦然。如果架構和服務器可以協同工作,那就好了:
但有可能面對(或者曾有過)下面的問題,當要把一個服務器和一個架構結合起來時,卻發現他們不是被設計成協同工作的:
那么,怎么可以不修改服務器和架構代碼而確保可以在多個架構下運行web服務器呢?答案就是Python Web Server Gateway Interface (或簡稱WSGI,讀作“wizgy”)。
WSGI允許開發者將選擇web框架和web服務器分開。可以混合匹配web服務器和web框架,選擇一個適合的配對。比如,可以在Gunicorn或者Nginx/uWSGI或者Waitress上運行Django, Flask,或Pyramid。真正的混合匹配,得益于WSGI同時支持服務器和架構: