flask源码笔记:三,app.py模块(1)——导入对象

来源:互联网 发布:真维斯淘宝 编辑:程序博客网 时间:2024/06/05 22:56
通过wc命令我们可以得知,app.py文件有1842行,所以这里就不一次性全部贴出来了。


(venv)[root@10-9-21-98 flask]# wc -l app.py
1842 app.py


查看模块描述:
"""
    flask.app
    ~~~~~~~~~


    This module implements the central WSGI application object.


    :copyright: (c) 2011 by Armin Ronacher.
    :license: BSD, see LICENSE for more details.
"""


可以得知:本模块就是flask框架产生WSGI应用的核心模块。


模块的前部分,仍然是对库和模块的导入,为了节约篇幅,我们对其直接后附分析
import os                                                                                            系统操作库
import sys                                                                                            环境操作库
from threading import Lock                                                               线程锁,用于避免竞争
from datetime import timedelta                         代表两个时间之间的的时间差,两个date或datetime对象相减时可以返回一个timedelta对象。                            
from itertools import chain                                 可以把一组迭代对象串联起来,形成一个更大的迭代器
from functools import update_wrapper            是wraps的主要功能提供者,它负责考贝原函数的属性,默认是:'__module__', '__name__', '__doc__', '__dict__'。


from werkzeug.datastructures import ImmutableDict       字面理解为一个产生不可变字典的工厂类
from werkzeug.routing import Map, Rule, RequestRedirect, BuildError           制作URL路由的组件
from werkzeug.exceptions import HTTPException, InternalServerError, \
     MethodNotAllowed, BadRequest                                                                 异常处理机制      


from .helpers import _PackageBoundObject, url_for, get_flashed_messages, \
     locked_cached_property, _endpoint_from_view_func, find_package           各种辅助函数
from . import json                                                                                                  json解析
from .wrappers import Request, Response                                                         请求工厂和相应工厂  
from .config import ConfigAttribute, Config                                                      配置文件工厂
from .ctx import RequestContext, AppContext, _AppCtxGlobals                       上下文管理器
from .globals import _request_ctx_stack, request, session, g                               全局和局部变量
from .sessions import SecureCookieSessionInterface                                         会话接口
from .module import blueprint_is_module                                                            判定蓝本的函数
from .templating import DispatchingJinjaLoader, Environment, \
     _default_template_ctx_processor                                                                        前端模板的全局环境变量和默认模板
from .signals import request_started, request_finished, got_request_exception, \
     request_tearing_down, appcontext_tearing_down                                            各种信号函数
from ._compat import reraise, string_types, text_type, integer_types                    暂且理解为自定义的数据类型


以上导入的对象,各自都实现了一些细节处理,而本模块的功能,就是利用这些功能组合起来,形成一个整合的对象。


接下来,是生成一个线程锁对象
# a lock used for logger initialization
_logger_lock = Lock()
注释说明了,是用于日志的初始化


def _make_timedelta(value):
    if not isinstance(value, timedelta):
    return timedelta(seconds=value)
    return value
该函数是一个私有的,将秒转换成timedelta对象的函数。


def setupmethod(f):
"""Wraps a method so that it performs a check in debug mode if the
    first request was already handled.
    """
    def wrapper_func(self, *args, **kwargs):
        if self.debug and self._got_first_request:
            raise AssertionError('A setup function was called after the '
                'first request was handled.  This usually indicates a bug '
                'in the application where a module was not imported '
                'and decorators or other functionality was called too late.\n'
                'To fix this make sure to import all your view modules, '
                'database models and everything related at a central place '
                'before the application starts serving requests.')
        return f(self, *args, **kwargs)
    return update_wrapper(wrapper_func, f)
该对象是一个装饰器。目的是校验Flask实例是否开启了debug模式并且获取第一个请求(从字面理解),如果是这样则报错。



0 0
原创粉丝点击