小提示:"{:0>3}".formate(9) 右对齐若小于3位 --->00n 0位占位符,> 表示右对齐
响应格式
请求格式
import socket
import os
# =========================================================
def ret(path):
dir = "../html/"
file = os.path.join(dir,path.strip(r"[/]"))
if os.path.exists(file):
with open(file,"rb") as f:
return f.read()
else:
with open(os.path.join(dir,"error.html"),"rb") as f:
return f.read()
# =========================================================
sk = socket.socket()
sk.bind(("127.0.0.1",8080))
sk.listen()
while True:
conn,_ = sk.accept()
data = conn.recv(8096)
data_str = str(data,encoding="utf8")
list = data_str.split("
")
# for i in list:
# print(i) # 获取每行,还可以通过 空格分隔 获取访问路径,根据路径返回不同那内容
# # 通过请求路径,建立字典,对应但会数据,可直接返回
firstLine = str(list[0]).split(' ')
temp = firstLine[1].split("?")
path = temp[0]
#print(path)
conn.send(b'http1.1 200
')
conn.send(ret(path))
conn.close()
sk.close()
"""
# http 请求
GET /sadasd/?name=dzf HTTP/1.1
Host: 127.0.0.1:8080
Connection: keep-alive
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36
Sec-Fetch-Mode: navigate
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,/;q=0.8,application/signed-exchange;v=b3
Sec-Fetch-Site: none
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7
'
"""
# =========================================================
"""
Python中 Web框架的分类:
1. web框架的本质:
socket服务端 与 浏览器的通信
2. socket服务端功能划分:
a. 负责与浏览器收发消息(socket通信) --> wsgiref/uWsgi/gunicorn... 自己写的长时间连接会报错
b. 根据用户访问不同的路径执行不同的函数
c. 从HTML读取出内容,并且完成字符串的替换(动态网站的本质) --> jinja2(模板语言)
1. 按上面三个功能划分:
1. 框架自带a,b,c --> Tornado
2. 框架自带b和c(和jinja2类似),使用第三方的a(wsgiref) --> Django
3. 框架自带b,使用第三方的a和c(jinja2) --> Flask
2. 按另一个维度来划分:
1. Django --> 大而全(你做一个网站能用到的它都有)
2. 其他 --> Flask 轻量级
"""
# 安装jinja2
from wsgiref.simple_server import make_server # a 功能
from jinja2 import Template # c功能
def index():
with open("09 jinja2版web框架.html", "r", encoding="utf-8") as f:
data = f.read()
template = Template(data) # 生成模板文件
# 从数据库中取数据
import pymysql
conn = pymysql.connect(