首页 > 其他 > 详细

flask源码之全局变量

时间:2021-05-29 20:09:15      阅读:32      评论:0      收藏:0      [点我收藏+]

引言:

  flask全局变量,里边包含了几乎常用的双下方法以及对这些方法flask又做了定制化,那么这样的话几乎教会了我们怎么去使用这些双下方法,并且有个生僻的东西叫偏函数(冻结函数)

 

代码:

  入口    import flask.globals

# -*- coding: utf-8 -*-

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."""


def _lookup_req_object(name):
    # name=request
    # _request_ctx_stack 就是globals中的 LocalStack() 对象
    # top方法拿到 requestContext也就是ctx 即 top=ctx
    top = _request_ctx_stack.top
    if top is None:
        raise RuntimeError(_request_ctx_err_msg)
    # 这里就相当于 去ctx中取request 
    return getattr(top, name)


def _lookup_app_object(name):
    top = _app_ctx_stack.top
    if top is None:
        raise RuntimeError(_app_ctx_err_msg)
    # name= request  这就是 ctx.push 中调用 requet_context 的 request=request_class
    return getattr(top, name)


def _find_app():
    # 这里同 request session g 同理
    top = _app_ctx_stack.top
    if top is None:
        raise RuntimeError(_app_ctx_err_msg)
    return top.app

"""
LocalStack LocalProxy Local
"""



# context locals
_request_ctx_stack = LocalStack()
_app_ctx_stack = LocalStack()

# 在使用 current_app 可以被直接导入使用 _find_app 从栈中拿到了程序的上下文 不过没有使用偏函数
current_app = LocalProxy(_find_app)
# 同 current_app 就可以在 视图函数中导入该 app
# capp=LocalProxy(partial(_lookup_app_object,‘app‘))

# 以后执行 函数 partial(_lookup_req_object, "request") 时 自动传递 request参数
# 查看源码 先去Local中拿到 RequestContext 对象 也就是ctx 这个对象中有request对象和session对象
# (_lookup_req_object, "request") 偏函数
request = LocalProxy(partial(_lookup_req_object, "request"))
#  同上 去ctx中获取 sesison
session = LocalProxy(partial(_lookup_req_object, "session"))
g = LocalProxy(partial(_lookup_app_object, "g"))

  这里变核心的代码 设计到 三个类    LocalStack    LocalProxy  Local 关系如下图

技术分享图片

 

flask源码之全局变量

原文:https://www.cnblogs.com/yuan-x/p/14825855.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!