第二十四节 让web服务器支持WSGI协议
2021-03-29 22:25
标签:turn RoCE frame sock _for 接收 argv for cmd命令 第二十四节 让web服务器支持WSGI协议 标签:turn RoCE frame sock _for 接收 argv for cmd命令 原文地址:https://www.cnblogs.com/kogmaw/p/12602541.htmlimport socket
import multiprocessing
import re
# import dynamic.mini_frame
import sys
# 通过sys.argv在cmd命令行给实例对象传参
class WSGIServer():
def __init__(self, port, app, static_path):
self.application = app
self.static_path = static_path
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.1.7‘,int(port)))
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)
if file_name == "/":
file_name = ‘\index.html‘
path = self.static_path + 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 =self.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():
if len(sys.argv) == 3:
try:
port = int(sys.argv[1])
frame_app_name = sys.argv[2]
except Exception as ret:
print(‘端口输入有误....‘)
return
else:
print(‘请按以下方式运行:‘)
print(‘python xxx.py 7890 mini_frame:application‘)
return
ret = re.match(r"([^:]+):(.*)", frame_app_name)
if ret:
frame_name = ret.group(1)
app_name = ret.group(2)
else:
print(‘请按以下方式运行:‘)
print(‘python xxx.py 7890 mini_frame:application‘)
print("...........................")
return
# 打开配置文件,进行路径读入
with open(‘web_server.conf‘) as fd:
conf_info = eval(fd.read())
‘‘‘{
"static_path":"E:\\360Downloads\\Software\\新建文件夹\\新建文件夹\\tmag_23_Infinity",
"dynamic_path":"./dynamic"
}‘‘‘
# sys.path 返回的是一个列表!该路径已经添加到系统的环境变量了,当我们要添加自己的搜索目录时,可以通过列表的append()方法
# 对于模块和自己写的脚本不在同一个目录下,在脚本开头加sys.path.append(‘xxx‘):
sys.path.append(conf_info[‘dynamic_path‘])
# 直接用import frame_name 不会将frame_name 认为是一个变量,直接认为是一个模块名
frame = __import__(frame_name)
app = getattr(frame, app_name)
wsgi_server = WSGIServer(port, app, conf_info["static_path"])
wsgi_server.run_forver()
if __name__ == ‘__main__‘:
main()
文章标题:第二十四节 让web服务器支持WSGI协议
文章链接:http://soscw.com/index.php/essay/69707.html