WSGI

WSGI(Web Sever Gateway Interface):分为服务器端Sever)和应用程序端App
服务器端:接收请求,给应用程序提供environ(环境信息)start_response(回调函数)。这个回调函数,返回httpheader数据以及status信息。
应用程序端:可调用对象,包括不仅限函数,类,含__call__方法的实例。用于处理请求,返回header/body/status给服务器。

【WSGI App】:
1、接收服务器端传来的environstart_response
2、回调函数接收两个参数:statusresponse_header
3、WSGI app通过回调函数,将response.header/status返回给WSGI server。
4、WSGI app最后再返回一个可迭代对象,就是response.body
def application(environ, start_response):    
	status = '200 OK'   # http状态码    
	response_headers = [('Content-type', 'text/plain')]  # 由二元tuple组成的list    
	start_response(status, response_headers)
	return iterator
PS:
1、回调函数必须在WSGI app返回可迭代数据之前被调用,因为它返回的是数据header部分且仅能调用一次
2、禁止回调函数直接将 response headers回传,必须把它们存储起来,直到WSGI app第一次迭代返回非空数据后,才能传递给客户端。

【WSGI Server】工作流程:
1、服务器创建socket连接,并监听端口,等待客户端连接;
2、接收到请求,解析客户端信息放到environ中,根据url调用对应的路由视图函数来处理;
3、视图函数解析http请求,再将methods、path、服务器数据等信息全部存入environ
4、WSGI sever调用WSGI app(应用程序),并将environstart_response传给WSGI app;
5、WSGI app将responseheader/status/body回传给WSGI sever;
6、视图函数通过socket将response信息传给客户端
def run(application):    
	environ = {}  #由server准备environ数据    
	def start_response(status, response_headers, exc_info=None):   #由server提供处理方法        
		pass    
	result = application(environ, start_response)  #调用WSGI app    
	def write(data):        
		pass    
	for data in result:  #迭代访问WSGI app返回header/status/body        
		write(data)

用middleware实现URL路由,对应用程序进行一层层的包装,就可以实现各种功能。这是框架的形成原理。


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值