第二十三节 让web服务器支持WSGI协议
2021-03-29 22:26
标签:动态 stat end 文件夹 dex lines request print __name__ 第二十三节 让web服务器支持WSGI协议 标签:动态 stat end 文件夹 dex lines request print __name__ 原文地址:https://www.cnblogs.com/kogmaw/p/12602536.htmlimport socket
import multiprocessing
import re
import dynamic.mini_frame
class WSGIServer():
def __init__(self):
self.web_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.web_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.web_socket.bind((‘192.168.0.106‘,7890))
self.web_socket.listen(128)
def tcp_serve(self, resp_socket):
recv_data = resp_socket.recv(1024).decode(‘utf-8‘)
request_lines = recv_data.splitlines()
file_name = ‘‘
ret = re.match(r"[^/]+(/[^ ]*)",request_lines[0])
if ret:
file_name=ret.group(1)
print(file_name)
if file_name == "/":
file_name = ‘\index.html‘
path = r‘E:\\360Downloads\\Software\\新建文件夹\\新建文件夹\\tmag_23_Infinity‘+file_name
if not file_name.endswith(".py"):
# 判断是都是.py结尾,不是返回动态页面,是返回静态页面
try:
f=open(path,‘rb‘)
except:
resp_data = ‘HTTP/1.1 200 OK\r\n‘ + "\r\n" + ‘.....file not find....‘
resp_socket.send(resp_data.encode(‘utf-8‘))
else:
html_content = f.read()
f.close()
resp_data = ‘HTTP/1.1 200 OK\r\n‘ + "\r\n"
resp_socket.send(resp_data.encode(‘utf-8‘))
resp_socket.send(html_content)
else:
# 动态页面处理
env= dict()
env[‘PATH INFO‘] = file_name
# 调用mini_frame框架里的application函数,返回header和body,在将两者在web服务器里组装,返回给浏览器
body =dynamic.mini_frame.application(env, self.set_response_headers)
header = ‘HTTP/1.1 %s\r\n‘ % self.status
for temp in self.headers:
header += "%s:%s\r\n" % (temp[0], temp[1])
header += "\r\n"
resp_data = header +body
resp_socket.send(resp_data.encode(‘utf-8‘))
resp_socket.close()
def set_response_headers(self,status,headers):
‘‘‘该方法用于接收mini_frame框架里返回的header数据‘‘‘
self.status = status
self.headers = [(‘Server‘,‘mini_web v8.8‘)]
self.headers += headers
def run_forver(self):
while True:
resp_socket, resp_addr = self.web_socket.accept()
p = multiprocessing.Process(target=self.tcp_serve, args=(resp_socket,))
p.start()
# 同乌班图一样也需要关闭套接字,跟文件描述符有关,不然页面一直刷新不出来
resp_socket.close()
# self.web_socket.close()
def main():
wsgi_server = WSGIServer()
wsgi_server.run_forver()
if __name__ == ‘__main__‘:
main()
文章标题:第二十三节 让web服务器支持WSGI协议
文章链接:http://soscw.com/index.php/essay/69712.html