上篇笔记有有了WSGI。
复习一下:
WSGI是一套关于程序端和服务器端的规范,或者说统一的接口。(程序端和服务器之间的中间件)
下面的示意图可以看出客户端,服务器,WSGI,程序之间的关系。
- 从flask程序开始,要运行 web 应用,必须要有 web server,使用 run()方法运行应用时创建了WSGIServer,继承自werkzeug 中的BaseServer。然后一直被继承,不断被重写。
- WSGI 看成中间件,WSGI中有一个非常重要的概念:每个 python web 应用都是一个可调用(callable)的对象(类定义时写了
__call__
方法)。 - Flask 类中的
__call__
方法会调用wsgi_app()
方法,wsgi_app()
的作用就是找到各种请求处理函数,调用这些函数,将处理结果返回到服务器。
图片来自WSGI: The Server-Application Interface for Python
有了上面的知识,从最简单的这个flask程序来看WSGI的实现。
- 使用
app.run()
方法来启动flask应用(app.run()
代码隐藏着创建一个服务器),app应用本身会作为参数传递到WSGI服务器中。 - 在客户端(这里就是浏览器)输入网址(发送一个请求),服务器使用WSGI 中间件来处理这个请求。
- WSGI 处理请求对应着
wsgi_app(self, environ, start_response)
方法,self
参数对应着app
,即flask程序;environ
和start_response
由服务器提供。 wsgi_app()
作用就是调用各种请求处理函数来处理请求,然后返回处理结果。即用户输入网址后,看到了网页响应。
from flask import Flask
app = Flask(__name__)
#生成app实例,传递 __name__参数,__name__ 就是当前模块名字。
@app.route("/")
def index():
return "2017-08-21"
if __name__ == '__main__':
app.run(debug=True)
1 首先
app.run()
方法开始。 看
run()
方法的定义,调用了werkzeug库中的一个
run_simple()
方法,最后启动了
BaseWSGIServer
服务器。 运行
run()
方法是只传递了
debug=True
参数。 看
run()
方法内部:
- 第一个 if 语句设置默认host参数值为 127.0.0.1
- 第二个 if 语句设置默认port参数值为5000
- 第三个 if 语句中传递了debug 参数值为 True
- the options to be forwarded to the underlying Werkzeug server. 这里把debug状态传递到底层的Werkzeug server。
即use_reloader=True ; use_debugger=True
- 最后调用werkzeug库中的一个
run_simple()
方法。同时,传递了刚刚设置的几个参数
def run(self, host=None, port=None, debug=None, **options):
"""Runs the application on a local development server.
...
"""
from werkzeug.serving import run_simple
if host is None:
host = '127.0.0.1'
if port is None:
server_name = self.config['SERVER_NAME']
if server_name and ':' in server_name:
port = int(server_name.rsplit(':', 1)[1])
else:
port = 5000
if debug is not None:
self.debug = bool(debug)
options.setdefault('use_reloader', self.debug)
options.setdefault('use_debugger', self.debug)
try:
run_simple(host, port, self, **options)
finally:
self._got_first_request = False
2 看
run_simple()
方法:
hostname, port, application
对应着刚才run()
方法中传递过来的host, port, self
参数。(这里self 就是Flask实例化了的app)- 同时
run()
方法中还传递了user_debugger=True;user_loader=True
。剩余的参数使用初始值。 - 根据上面
user_loader=True
,第一个if语句成立,调用了werkzeug.debug
模块中的DebuggedApplication
类来对应用程序包装一次。传入了application
参数和use_evalex
参数,调用run_simple()
方法时设置了use_evalex=True
。
DebuggedApplication
类的简单说明:
Enables debugging support fo