简介
WSGI:Web Server Gateway Interface
web服务器和web应用程序之间的一种简单而通用的接口,接收请求的Server和处理请求的Application
Server收到一个请求后,通过Socket把环境变量和一个Callback回调函数传递给后端Application,Application完成页面组转后再通过Callback把内容返回给Server
最后Server再把响应返回给Client。
应用程序接口
WSGI应用接口实现为一个可调用对象:函数,方法,类或者任何一个实现call方法的对象,必须接收俩个位置参数
- 包含CGI环境变量的字典
- 一个可调用函数对象,让应用程序调用来向服务器提交HTTP状态码和HTTP响应头
其基本骨架如下:
import os
def app(environ,start_response):
file_name = environ['PATH_INFO'][1:]
HTML_ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
try:
file = open(os.path.join(HTML_ROOT_DIR,file_name),'rb')
except IOError:
status = '404 Not Found'
start_response(status,[('Content-Type','texl.html')])
response = 'This file not found'
else:
status = '200 OK'
start_response(status,[('Content-Type','texl.html')])
file_data = file.read()
file.close()
response = file_data.decode('utf-8')
return [response.encode('utf-8')]
如何调用application()函数呢?environ和start_response这2个参数需要从服务器获取,application函数必须由WSGI服务器来调用
现在很多服务器都符合WSGI规范,像Apache服务器和Nginx服务器等,python内置WSGI服务器,wsgiref模块
from wsgiref.simple_server import make_server
from application import app
httpd = make_server("",8000,app)
print('Serving HTTP on port 8000...')
httpd.serve_forever() #持续运行
httpd.handle_request() #运行一次后退出