第二十三节 让web服务器支持WSGI协议
Posted kog_maw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第二十三节 让web服务器支持WSGI协议相关的知识,希望对你有一定的参考价值。
import 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 ‘ + " " + ‘.....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 ‘ + " " 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 ‘ % self.status for temp in self.headers: header += "%s:%s " % (temp[0], temp[1]) header += " " 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协议的主要内容,如果未能解决你的问题,请参考以下文章