Flask内部执行原理
Flask Context Works:
请求进来之后:
0. 先绑定路由映射
1. Flask.wsgi_app() 处理每一个请求
2. create & push RequestContext
3. RequestContext create & push APPContext
current_app, g, request, session 可用
4. 调用view函数
Flask Signals
特点:all signal handlers are executed in undefined order and do not modify any data.(执行没有顺序且不能修改数据)
If signals_available is true, the following signals are sent:
1.request_started在before_request()函数被调用前就被发送
2.request_finished在after_request()函数被调用后发送
3.got_request_exception 在异常被处理前发送,
4.got_request_exception is sent when an exception begins to be handled, but before an errorhandler() is looked up or called.
5.request_tearing_down在teardown_request()函数执行后执行
Callbacks and Errors:
1. 执行请求前,先执行before_request函数
2. 如果before_request有返回值,则跳过其他before_request函数
3. 将before_request的返回值当做response 且 view function不在执行
4. 如果before_request没有response,则执行匹配成功的view function
5. 视图函数返回的response被转化为一个实际的response object 并传递给after_request function
6. after_reqeust function会返回一个修改后的/新的response object
7. response返回之后,开始调用teardown_request and teardowm_appcontext
8. 即使上面的步骤中引发了未处理异常,teardown_request and teardowm_appcontext 这两个函数也会被执行
注意:
1.如果执行teardown函数前抛出了异常,Flask会尽力使用一个errorhandler function来处理异常并返回一个response
2.如果没有error handler发现,Flask会返回一个500 Internal Server Error response,teardown函数依旧会被执行并传递exception 对象
请求处理完成:
1.执行 teardowm_request()
2.执行 teardowm_appcontext()
3.pop request_context
4.pop app_context
在请求结束时,请求上下文poped 并且 所有关联数据都会被销毁
请求进来
__call__
wsgi_app
create ReqeustContext object
push ctx
create application context and push
session(app, request)
send request : 包含调用视图函数
request_start.send()
rv = preprocess_request() action
自定义before_reqeust()????
view function
finalize_request(rv)
response = make_response(rv)
response = process_response(response)
save_session()
request_finished.send()
return response
return response
g object 的生命周期同app context,作用是用来存储请求的通用数据
-1.处理请求时,应用程序上下文自动被RequestContext push
-2.current_app 指向AppContext(用做with块推送上下文)
dispatch_request: 分发请求,匹配URL并返回视图或错误处理程序的返回值
===========================================
BluePrints and Views:
A Blueprint is a way to organize a group of related views and other code.
Rather than registering views and other code directly with an application,
they are registered with a blueprint.
Then the blueprint is registered with the application when it is available in the factory function.
蓝图是组织一组相关视图和其他代码的方法,而不是直接向应用程序注册视图和其他代码;他们使用蓝图注册的。
当蓝图在factory函数中可用,它就被注册到应用程序中
模板:
g 、url_for is automatically available in templates

浙公网安备 33010602011771号