wsgi接口规则:
开发者在开发web应用时实现统一名称的函数(即application()),就可以相应http请求了
application()函数的返回值会影响 body 体内容。
- evironment参数用于传递响应头,包括状态行和其他 Headers参数传递过程中以key-value的形式的dict对象进行传递
- response 参数用于处理传递 evironment 参数的 dict 对象,并形成上图中的响应头(Headers)样式; 是一个开始响应 HTTP 请求的函数(响应行、响应头),
- application()函数用于返回上图中的响应体(Body),包括网页数据、图片、音频等。
创建一个文件web_wsgi编写application函数
# 解析模板
def application(enviroment,response):
# 响应头的信息状态行和其他Headers
response('HTTP/1.1 200 OK',[("Content-type","text/html")])
# 响应体的内容
return body
创建一个文件web_server.py编写application函数
import os.path
import socket
from multiprocessing import Process
import re
# 导入文件
import web_wsgi
g_header=""
#处理请求头和状态行
def handle_header(status_line,headers):
global g_header
res_str=""
res_str += status_line+"\r\n"
for head in headers:
# head[0]:关键字 head[1]:值
res_str +=head[0]+":"+head[1]+"\r\n"
g_header=res_str
suffer_mapping = {
"html":"text/html;charset=utf-8",
"css":"text/css",
"js":"text/javascript",
"jpg":"image/jpeg",
"jpeg":"image/jpeg",
"png":"image/png",
"gif":"image:gif"
}
def handle_socket(client):
req_data = client.recv(1024)
con_lines = req_data.decode('utf-8').splitlines()
if len(con_lines) > 0:
first_line = con_lines[0]
file_path = re.match('\w+ (/[^ ]*)',first_line).group(1)
if file_path == '/':
file_path = '/index.html'
if file_path == '/favicon.ico':
# favicon.ico 图标文件是浏览器默认请求的,若 url 匹配到则直接返回
return
# 判断一下:如果请求的文件没有 404
if os.path.exists('.'+file_path):
# 有这个文件 - 读取文件内容
# 获取文件后缀
suffix = file_path.split('.')[-1] # html jpg png gif
# 没有这个文件 - 404
status_line = "HTTP/1.1 200 OK\r\n"
res_header = "Content-Type: "+suffer_mapping[suffix]+"\r\nAuthor:yao\r\ndate:2021-12-9\r\n"
body = ""
if file_path == "/index.html":
body=web_wsgi.application(env,handle_header)
# 响应信息
res_data = g_header + "\r\n" + body
res_data = res_data.encode('utf-8')
# 图片
elif suffix in ['jpg', 'jpeg', 'png', 'gif']:
with open('.' + file_path, 'rb') as imgFile:
body = imgFile.read()
# 响应信息
res_data = (status_line + res_header + "\r\n").encode('utf-8') + body
else:
with open('.'+file_path,'rb') as htmlFile:
body = htmlFile.read().decode('utf-8')
# 响应信息
res_data = status_line + res_header + "\r\n" + body
res_data = res_data.encode('utf-8')
else:
# 没有这个文件 - 404
status_line = "HTTP/1.1 404 Not Found\r\n"
res_header = "Content-Type: text/html;charset=utf-8\r\nAuthor:yuan\r\ndate:2021-12-9\r\n"
body = "404 not found"
# 响应信息
res_data = status_line + res_header + "\r\n" + body
res_data = res_data.encode('utf-8')
# 发送
client.send(res_data)
client.close()
def main():
# socket对象
socket_server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# 解决端口冲突
socket_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# 绑定地址和端口 - 元组 (ip地址,端口号)
socket_server.bind(('',9002))
# 监听
socket_server.listen(10)
while True:
# 接收用户请求
client_socket,client_addr = socket_server.accept()
# 创建一个处理用户请求的子进程
process = Process(target=handle_socket,args=(client_socket,))
# 启动
process.start()
# 断掉客户端
client_socket.close()
if __name__ == '__main__':
main()