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):
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:
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':
return
if os.path.exists('.'+file_path):
suffix = file_path.split('.')[-1]
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:
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_server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
socket_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
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()
|