介绍
wsgi server
wsgi规定符合wsgi规范的wsgi服务器需要完成以下事情:
- 接收来自HTTP客户端的request请求
- 按照wsgi规范调用wsgi应用程序
- 把处理好的结果返回给客户端
wsgi application
wsgi规定wsgi应用程序是一个callable对象,当有请求过来时,wsgi服务器 会调用这个wsgi应用程序
wsgi 应用程序可以是:
- 方法
- 函数
- 实现了__call__方法的一个类的实例
- 一个类,用这个类生成实例的过程就相当于调用这个类
接受参数:environ, start_response,exc_info(可选)
- environ(环境变量): HTTP请求的所有输入信息都可以通过environ获得
- start_response: 一个callbale函数。 接受两个参数status(状态码)和response_headers(参数列表)
- exc_info: 错误处理的时候使用
返回值:一个iterator对象,这个iterator就是repsonse body
wsgi middleware
中间件是为了是应用程序有额外的行为而存在的。 中间件可以随便决定是否放在程序的前面。否则就不是中间件而是程序的一部分
使用
def application(environ, start_response):
start_response('200 OK', [('Content-Type','text/html')])
return '<h1> hello {}</h1>'.format(environ["PATH_INFO"][1:] or "World"))
from wsgiref.simple_server import make_server
from app import application
#创建一个http服务器,ip地址为空,端口:8888,调用函数application
httpd = make_server('',8888, application)
print("HTTP Server starting on port 8888 ...")
# 开始监听http请求
httpd.serve_forever()
启动wsgi server
python server.py
访问地址
http://127.0.0.1:8888/magicops
返回内容
Hello magicops
WSGI参考:https://www.python.org/dev/peps/pep-3333/
wsgiref参考:https://pypi.org/project/wsgiref/