简介


WSGI:Web Server Gateway Interface
web服务器和web应用程序之间的一种简单而通用的接口,接收请求的Server和处理请求的Application
Server收到一个请求后,通过Socket把环境变量和一个Callback回调函数传递给后端Application,Application完成页面组转后再通过Callback把内容返回给Server
最后Server再把响应返回给Client。

应用程序接口


WSGI应用接口实现为一个可调用对象:函数,方法,类或者任何一个实现call方法的对象,必须接收俩个位置参数

  1. 包含CGI环境变量的字典
  2. 一个可调用函数对象,让应用程序调用来向服务器提交HTTP状态码和HTTP响应头

其基本骨架如下:

  1. import os
  2. def app(environ,start_response):
  3. file_name = environ['PATH_INFO'][1:]
  4. HTML_ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
  5. try:
  6. file = open(os.path.join(HTML_ROOT_DIR,file_name),'rb')
  7. except IOError:
  8. status = '404 Not Found'
  9. start_response(status,[('Content-Type','texl.html')])
  10. response = 'This file not found'
  11. else:
  12. status = '200 OK'
  13. start_response(status,[('Content-Type','texl.html')])
  14. file_data = file.read()
  15. file.close()
  16. response = file_data.decode('utf-8')
  17. return [response.encode('utf-8')]

如何调用application()函数呢?environ和start_response这2个参数需要从服务器获取,application函数必须由WSGI服务器来调用
现在很多服务器都符合WSGI规范,像Apache服务器和Nginx服务器等,python内置WSGI服务器,wsgiref模块

  1. from wsgiref.simple_server import make_server
  2. from application import app
  3. httpd = make_server("",8000,app)
  4. print('Serving HTTP on port 8000...')
  5. httpd.serve_forever() #持续运行
  6. httpd.handle_request() #运行一次后退出