为什么要使用wsgi协议

試著忘記壹切 提交于 2019-12-24 23:07:50

一个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_headerdef 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”))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!