importsocketimportsysfrom multiprocessing importProcessclassWSGIServer(object):
addressFamily=socket.AF_INET
socketType=socket.SOCK_STREAM
requestQueueSize= 100server_response_header= ""
def __init__(self, server_info, application):
server_socket=socket.socket(self.addressFamily, self.socketType)#允许重复使用上次的套接字绑定的port
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)#绑定
server_socket.bind(server_info)#变为被动,并制定队列的长度
server_socket.listen(self.requestQueueSize)
self.server_socket=server_socket
self.application=applicationdefwait_client(self):'循环运行web服务器,等待客户端的链接并为客户端服务'
whileTrue:#等待新客户端到来
new_socket, address =self.server_socket.accept()#多进程服务器,并发服务器于多个客户端
process = Process(target=self.handle_client, args=(new_socket,))
process.start()#因为创建的新进程中,会对这个套接字+1,所以需要在主进程中减去依次,即调用一次close
new_socket.close()defhandle_client(self, new_socket):'用一个新的进程,为一个客户端进行服务'get_client_data= new_socket.recv(2048)
lines=str(get_client_data).splitlines()
request_data= str(lines[0]).split(" ")try:
file_name= request_data[1]
method=request_data[0]exceptIndexError as e:print(e)returnFalse#根据接收到的请求头构造环境变量字典
env ={"PATH_INFO": file_name,"METHOD": method
}#调用应用的相应方法,完成动态数据的获取
response_body =self.application(env, self.start_response)
response= self.server_response_header +response_body
new_socket.send(response.encode("utf-8"))
new_socket.close()defstart_response(self, status, header):
headers= "HTTP/1.0" + status + "\r\n"
for h inheader:
headers+= "%s : %s\r\n" %h
self.server_response_header= headers + "\r\n"
defmain():if len(sys.argv) < 2:
sys.exit('请按照要求,指定模块名称:应用名称,例如 module:callable')#获取module:callable
appPath = sys.argv[1]#根据冒号切割为module和callable
module, application = appPath.split(':')
module_root= "./module"
#添加路径套sys.path
sys.path.insert(0, module_root)#动态导入module变量中指定的模块
module = __import__(module)#获取module变量中指定的模块的,application变量指定的属性
application =getattr(module, application)
wsgi_server= WSGIServer(("", 8081), application)
wsgi_server.wait_client()if __name__ == '__main__':
main()