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同时支持服务器和架构: