从第一行开始看起

从官方实例中, 我们可以看到这样一个import 以及实例化Flask类的操作,接下来就深入源码看一下 http 请求前,Flask 都干了什么。

from flask import Flask
app = Flask(__name__)  # 参考Python相关/__name__是什么
app.secret_key = SECRET_KEY
app.debug = DEBUG

深入 Flask 类定义中来查看

class Flask(object):
    """The flask object implements a WSGI application and acts as the central
    object.  It is passed the name of the module or package of the
    application.  Once it is created it will act as a central registry for
    the view functions, the URL rules, template configuration and much more.

    The name of the package is used to resolve resources from inside the
    package or the folder the module is contained in depending on if the
    package parameter resolves to an actual python package (a folder with
    an `__init__.py` file inside) or a standard module (just a `.py` file).

    For more information about resource loading, see :func:`open_resource`.

    Usually you create a :class:`Flask` instance in your main module or
    in the `__init__.py` file of your package like this::

        from flask import Flask
        app = Flask(__name__)
    """
    # 此处注释大概介绍了如何实例化一个 Flask 对象,介绍了 Flask 的是如何实现的。

    #: the class that is used for request objects.  See :class:`~flask.request`
    #: for more information.
    request_class = Request
    # 此处继承了 werkzeug 框架的 Request 类,把 http request 抽象成一个类

    #: the class that is used for response objects.  See
    #: :class:`~flask.Response` for more information.
    response_class = Response
    # 此处同上, 抽象的是 http response

    #: path for the static files.  If you don't want to use static files
    #: you can set this value to `None` in which case no URL rule is added
    #: and the development server will no longer serve any static files.
    static_path = '/static'
    # 静态资源文件路径

    #: if a secret key is set, cryptographic components can use this to
    #: sign cookies and other things.  Set this to a complex random value
    #: when you want to use the secure cookie for instance.
    secret_key = None
    # 加密 cookie 的设置

    #: The secure cookie uses this for the name of the session cookie
    session_cookie_name = 'session'
    # session 名称

    #: options that are passed directly to the Jinja2 environment
    jinja_options = dict(
        autoescape=True,
        extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_']
    )
    # jinja2 设置

接下来是 __init__ 方法

到此处 其实才算真正的执行完

继续往下看, connect_db 和 init_db 两个函数都是操作数据库的函数, 暂且不表。到了下一个函数before_request 有一个装饰器

继续看实现路由的装饰器

详细看下 add_url_rule

综上,Flask 会通过装饰器的形式,把你所写的 url 转发规则以及函数一一映射并且存储起来。

定义完了路由之后,来启动 app 吧~

Last updated