一个cs模型是由服务器和客户端组成,大多相互状况下也就是服务器端和浏览器之间的通讯。经过浏览器请求服务器,而后服务器再响应浏览器。html
那么若是浏览器想要请求一个python文件,例如http://127.0.0.1:8000/time.py/那么该如何实现。python
首先若是浏览器只请求相似index.html的时候只要server中拥有这个index.html。而且构建一个“状态码+响应头+“\r\n”+响应体”将index.html的源代码做为响应体传入浏览器就能够实现静态页面的请求响应。浏览器
首先有这样一个想法构建一个相似请求静态页面的那样一个响应字符串。将响应体做为python程序的返回值传入浏览器会有什么样的结果。以下图服务器
也就是说这是没办法实现和咱们想象的中的那样。app
引入接口这个概念,前辈们的不懈努力完成了wsgi协议。也就是只要咱们能够实现wsgi接口而后经过服务器来调用这个接口就能够实现浏览器请求python文件。socket
python程序(ctime.py):server
import timehtm
def application(env,start_response):
stauts = "200 ok"
headers = [("Content-Type","text/plain")]
start_response(stauts,headers)
return time.ctime()blog
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”))