Flask源码:globals.py(全局上下文)

# -*- coding: utf-8 -*-
"""
    flask.globals
    ~~~~~~~~~~~~~

    Defines all the global objects that are proxies to the current
    active context.

    :copyright: 2010 Pallets
    :license: BSD-3-Clause
"""
from functools import partial    #偏函数

from werkzeug.local import LocalProxy
from werkzeug.local import LocalStack


#默认的错误信息
_request_ctx_err_msg = """\
Working outside of request context.

This typically means that you attempted to use functionality that needed
an active HTTP request.  Consult the documentation on testing for
information about how to avoid this problem.\
"""
_app_ctx_err_msg = """\
Working outside of application context.

This typically means that you attempted to use functionality that needed
to interface with the current application object in some way. To solve
this, set up an application context with app.app_context().  See the
documentation for more information.\
"""

#三个模块方法,封装request栈和app栈的栈顶信息
def _lookup_req_object(name):
    top = _request_ctx_stack.top
    if top is None:
        raise RuntimeError(_request_ctx_err_msg)
    return getattr(top, name)


def _lookup_app_object(name):
    top = _app_ctx_stack.top
    if top is None:
        raise RuntimeError(_app_ctx_err_msg)
    return getattr(top, name)


def _find_app():
    top = _app_ctx_stack.top
    if top is None:
        raise RuntimeError(_app_ctx_err_msg)
    return top.app


# context locals
#全局请求上下文栈
_request_ctx_stack = LocalStack()
#全局App上下文栈
_app_ctx_stack = LocalStack()
#当前App上下文栈顶
current_app = LocalProxy(_find_app)
#当前请求栈栈顶request环境信息,用偏函数封装调用
request = LocalProxy(partial(_lookup_req_object, "request"))
#当前请求栈栈顶session环境信息,用偏函数封装调用
session = LocalProxy(partial(_lookup_req_object, "session"))
g = LocalProxy(partial(_lookup_app_object, "g"))

"""
线程安全在LocalProxy和LocalProxy中实现
"""
发布了23 篇原创文章 · 获赞 0 · 访问量 2016

猜你喜欢

转载自blog.csdn.net/qq_33913982/article/details/104251343
今日推荐