为什么要使用wsgi协议

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

为什么要使用wsgi协议

wss9806   2019-12-24 我要评论

一个cs模型是由服务器和客户端组成,大多相互情况下也就是服务器端和浏览器之间的通信。通过浏览器请求服务器,然后服务器再响应浏览器。

那么如果浏览器想要请求一个python文件,例如http://127.0.0.1:8000/time.py/那么该如何实现。

首先如果浏览器只请求类似index.html的时候只要server中拥有这个index.html。并且构建一个“状态码+响应头+“\r\n”+响应体”将index.html的源代码作为响应体传入浏览器就可以实现静态页面的请求响应。

首先有这样一个想法构建一个类似请求静态页面的那样一个响应字符串。将响应体作为python程序的返回值传入浏览器会有什么样的结果。如下图

 

 

 也就是说这是没办法实现和我们想象的中的那样。

引入接口这个概念,前辈们的不懈努力完成了wsgi协议。也就是只要我们可以实现wsgi接口然后通过服务器来调用这个接口就可以实现浏览器请求python文件。

python程序(ctime.py):

import time

def application(env,start_response):
  stauts = "200 ok"
  headers = [("Content-Type","text/plain")]
  start_response(stauts,headers)
  return time.ctime()

server端(伪代码):  

def start_response(self,statu_num,response_headers):
self.response_statu_num = statu_num
response_header = “”
for header in response_headers:
response_header += “%s: %s”%(header)
self.response_headers = response_header
def handla_file(self):
ctime = __import__(模块名)
response_body = ctime.application(environ,start_response)
response_data= response_statu_num+response_headers+”\r\n”+response_body
client_socket.send(bytes(response_data,”utf-8”))

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们