NO.2 Python Web 服务器
零蚀
浏览器访问服务器
-
返回Web静态页面
- Client-HTTP请求的方式
tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 连接TCP服务器 tcp_socket.connect(("tangyangapp.com", 80)) # 发送TCP请求(HTTP协议) # 请求行 req_line = "GET / HTTP/1.1\r\n" # 请求头 req_head = "User-Agent: HmBrowser/5.0\r\n" # 空行 req_empty = "\r\n" req_data = (req_line + req_head + req_empty).encode() tcp_socket.send(req_data) recv = tcp_socket.recv(1024 * 4) print(recv.decode()) tcp_socket.close()
- 响应数据
HTTP/1.1 400 Bad Request Server: nginx Date: Sat, 01 Feb 2020 04:28:19 GMT Content-Type: text/html Content-Length: 150 Connection: close \r\n <html> <head><title>400 Bad Request</title></head> <body> <center><h1>400 Bad Request</h1></center> <hr><center>nginx</center> </body> </html>
截出请求体:
index = recv.decode().find("\r\n\r\n") body = recv.decode()[index + 4:]
-
Server-HTTP返回固定数据
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind(("", 8886)) server_socket.listen(1024) while True: client, ip_port = server_socket.accept() recv = client.recv(1024 * 4).decode() # 状态行 line = "HTTP/1.1 200 OK\r\n" # 响应头 head = "server:ZERO/1.5\r\n" # 响应体 body = "hello world" client.send((line + head + "\r\n" + body).encode()) client.close()
-
Server返回固定页面
-
导入静态网站
-
代码部分
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind(("127.0.0.1", 8886)) server_socket.listen(1024) while True: client, ip_port = server_socket.accept() recv = client.recv(1024 * 4).decode() # 状态行 line = "HTTP/1.1 200 OK\r\n" # 响应头 head = "server:ZERO/1.5\r\n" head += "Content-Type: text/html;charset=utf-8\r\n" # 响应体 with open("static/index.html", "rb") as file: body = file.read() client.send((line + head + "\r\n").encode() + body) client.close()
with open() as file 的优点 一是为了代码简洁,二是节省了file.close() 的方法。
- 访问获取:
这里我们也可以用请求的recv信息截取到path,来指定打开哪一个html,例如:127.0.0.1:8886/index2.html访问。
如果用这种方式来截取路径,来指定页面,需要try…catch…
-
-
-
Jinja
- 安装
pip install jinja2
- 替换网页内容
from jinja2 import Environment, FileSystemLoader t_env = Environment(loader=FileSystemLoader("./templates/")) template = t_env.get_template("index.html") data = template.render( content1="aaaa" )
data是将index网页的的{{ content1 }}字符换置成content1赋值内容aaaa。
- 防止端口占用,释放端口
server_socket.setsockopt(socket.SOL_SOCKET, socket.SOCK_STREAM, True)
-
动态资源请求WSGI
- 图解
动态页面一般有 .jsp .php 等
- 多进程
import multiprocessing def func(args): pass # 申请一个进程 multi = multiprocessing.Process(target=func(),args=("arg",)) # 开启进程 multi.start()
🔗 前言
🔗 Python 高级列表
🔗 NO.1 Python网络通信
🔗 NO.3 Python多线程&锁
🔗 NO.4 Python多进程
🔗 NO.5 Python协程&生成器
🔗 NO.6 Python正则&爬虫初
🔗 NO.7 Python操作MySQL
🔗 NO.8 Python Spider
🔗 NO.9 Python 装饰器&other