推荐两篇文章:
http://www.jianshu.com/p/2a2407f66438
https://blog.tonyseek.com/post/the-context-mechanism-of-flask/
推荐先看第一篇,再看第二篇
第一篇对请求处理的流程进行了梳理,
第二篇分析了一些细节,并且说明了使用栈结构的原因。
>>> from flask.globals import _app_ctx_stack, _request_ctx_stack
>>> from flask import Flask
>>> app = Flask(__name__)
>>> _app_ctx_stack._local.__storage__
{}
>>> _request_ctx_stack._local.__storage__
{}
>>> app.test_request_context()
<RequestContext 'http://localhost/' [GET] of __main__>
>>> _request_ctx_stack._local.__storage__
{}
>>> _app_ctx_stack._local.__storage__
{}
>>> req = app.test_request_context()
>>> req.push()
>>> _request_ctx_stack._local.__storage__
{<greenlet.greenlet object at 0x7f93e8177178>: {'stack': [<RequestContext 'http://localhost/' [GET] of __main__>]}}
>>> req.push()
>>> _request_ctx_stack._local.__storage__
{<greenlet.greenlet object at 0x7f93e8177178>: {'stack': [<RequestContext 'http://localhost/' [GET] of __main__>, <RequestContext 'http://localhost/' [GET] of __main__>]}}
>>> req.pop()
>>> _request_ctx_stack._local.__storage__
{<greenlet.greenlet object at 0x7f93e8177178>: {'stack': [<RequestContext 'http://localhost/' [GET] of __main__>]}}
>>> _request_ctx_stack.top.request
<Request 'http://localhost/' [GET]>