flask源码分析(一)
2026-09-13 20:12:59 # flask

对于flask源码,已经看过几次,每次都是看了忘,忘了看,这次就好生记录一下。也算是认真学习。

Flask class

1
2
from flask import Flask
app = Flask(__name__)

一般 我们都是这样开头的,那我们就 从最开始的 __name__ 开始介绍。

Flask 的一个参数 import_name

通过进入源码了解到:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
admonition:: About the First Parameter
The idea of the first parameter is to give Flask an idea of what
belongs to your application. This name is used to find resources
on the filesystem, can be used by extensions to improve debugging
information and a lot more.

So it's important what you provide there. If you are using a single
module, `__name__` is always the correct value. If you however are
using a package, it's usually recommended to hardcode the name of
your package there.

For example if your application is defined in :file:`yourapplication/app.py`
you should create it with one of the two versions below::

app = Flask('yourapplication')
app = Flask(__name__.split('.')[0])

Why is that? The application will work even with `__name__`, thanks
to how resources are looked up. However it will make debugging more
painful. Certain extensions can make assumptions based on the
import name of your application. For example the Flask-SQLAlchemy
extension will look for the code in your application that triggered
an SQL query in debug mode. If the import name is not properly set
up, that debugging information is lost. (For example it would only
pick up SQL queries in `yourapplication.app` and not
`yourapplication.views.frontend`)
##### 谷歌翻译
告诫::关于第一个参数

第一个参数的想法是让Flask了解属于您的应用程序。此名称用于查找资源在文件系统上,扩展可以使用它来改进调试信息等等。

因此,您在此处提供的内容很重要。如果您使用单个在模块中,“ __ name__”始终是正确的值。如果你是使用软件包,通常建议对代码名称进行硬编码您的包裹在那里。

例如,如果您的应用程序是在:file:`yourapplication / app.py`中定义的
您应该使用以下两个版本之一创建它::
app = Flask('yourapplication')
app = Flask(__name__.split('.')[0])

这是为什么?由于如何查找资源,该应用程序甚至可以与“ __name__”一起使用。但是,这会使调试更加痛苦。某些扩展可以根据您的应用程序的导入名称进行假设。例如,Flask-SQLAlchemy扩展将在您的应用程序中查找在调试模式下触发SQL查询的代码。如果导入名称设置不正确,则该调试信息将丢失。 (例如,它将仅在`yourapplication.app`中而不是`yourapplication.views.frontend`中拾取SQL查询。)

第一个参数 单模块

如果只是使用单模块,那么使用__name__ 总是对的。

什么是单模块就是一个文件搞定所有。

第一个参数 多内容

目录结构是:
├─.idea
│ └─inspectionProfiles
├─to_the_world_package
│ ├─static
│ └─templates
└─pycache

file: to_the_world_package/to-the-world.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import os
import sys

from flask import Flask, render_template
from flask.helpers import get_root_path
from .hello import data

print(__name__)
app = Flask("to_the_world_package")
# app = Flask(__name__.split(".")[0])
# app = Flask(__name__)

print(app.import_name)
print(app.template_folder)
print(app.root_path)
import_name = "to_the_world_package"
mod = sys.modules.get(import_name)
print(mod.__file__)
print(os.path.abspath(mod.__file__))
print(os.path.dirname(os.path.abspath(mod.__file__)))

import_name = "to_the_world_package.to-the-world"
mod = sys.modules.get(import_name)
print(mod.__file__)
print(os.path.abspath(mod.__file__))
print(os.path.dirname(os.path.abspath(mod.__file__)))


@app.route("/")
def index():
print(data)
return render_template("index.html")


if __name__ == '__main__':
# app.run(debug=True, host='0.0.0.0', port=8080)
app.run(debug=True, port=8080)
"""
to_the_world_package.to-the-world
to_the_world_package.to-the-world
templates
C:\Users\libai\dfk-common\日常\flask-rbac\to_the_world_package
# import_name = "to_the_world_package"
C:\Users\libai\dfk-common\日常\flask-rbac\to_the_world_package\__init__.py
C:\Users\libai\dfk-common\日常\flask-rbac\to_the_world_package\__init__.py
C:\Users\libai\dfk-common\日常\flask-rbac\to_the_world_package
# import_name = "to_the_world_package.to-the-world"
C:\Users\libai\dfk-common\日常\flask-rbac\to_the_world_package\to-the-world.py
C:\Users\libai\dfk-common\日常\flask-rbac\to_the_world_package\to-the-world.py
C:\Users\libai\dfk-common\日常\flask-rbac\to_the_world_package
"""

从这里来看 无论使用 __name__ 还是 packeage_name 还是 __name__.split(".")[0] 都可以,因为

get_root_path方法 会把root_path给改回来。

Flask 的第一个参数 主要是 为了 让Flask找文件位置,就是找到所谓的root_path,然后就可以找到root_path下的文件,例如 static 或者 templates,如果root_path位置不对,就会无法使用 static 或者 templates,因此可以自己设定位置,设定 static_folder,template_folder,或者直接设置root_path

1
2
3
4
5
6
7
8
9
10
11
12
13
def __init__(
self,
import_name,
static_url_path=None,
static_folder="static",
static_host=None,
host_matching=False,
subdomain_matching=False,
template_folder="templates",
instance_path=None,
instance_relative_config=False,
root_path=None,
):

这里写一个真实的

目录精简下来:

app:

├─.idea
│ └─inspectionProfiles
├─config
│ └─config.py
├─controllers
│ ├─app
│ ├─impl
│ ├─web
│ └─wx
├─log
├─models
├─static
│ └─dept_img
└─Main.py

我们在config目录下的 config.py中进行了配置,但是在主目录下Main.py进行注册启动。

因此 我们config下的config.py中如何写 Flask呢?

我去看看了以前的

以前我们是设定template_folder 和 static_folder
1
app = Flask(__name__, template_folder='../templates', 和 static_folder="../static", static_url_path="/static")
现在我们知道第一个参数的意义,那我们可以直接这样写就可以了
1
2
3
4
5
6
7
8
9
print(__name__)
app = Flask("app")
print(app.root_path)

"""
config.config
I:\libaibuaidufu\app
此时的app,root_path 就是对的。
"""