我正在开发一个(按照我的标准)大型 Flask 项目(5000 行 Python 代码,而且只完成了一半)。客户希望项目是模块化的,所以我采用了这种方法:
我的文件夹结构如下:
├── __init__.py
├── modules.yml
├── config
├── controllers
│ └── ...
├── lib: Common functions I use often
│ └── ...
├── models
│ └── ...
├── static: All static files
│ ├── css
│ ├── img
│ └── js
└── templates: Jinja2 templates
└── ...
在modules.yml 中,我定义了我的模块,包括名称和 URL。这样,客户无需接触单个 Python 文件即可启用/禁用模块。另外,我根据模块列表生成菜单。按照惯例,每个模块在controllers/ 中都有它自己的Python 模块,它将从models/ 加载它的model。每个控制器都定义了一个Blueprint 存储为控制器的名称。例如。对于user 模块,我在controllers/user.py:
# Module name is 'user', thus save Blueprint as 'user' variable
user = Blueprint('user', __name__)
@user.route('/user/')
def index():
pass
这样,我可以读取我的__init__.py 中的modules.yml 并动态加载和注册所有启用的模块:
# Import modules
for module in modules:
# Get module name from 'url' setting, exculde leading slash
modname = module['url'][1:]
try:
# from project.controllers.<modname> import <modname>
mod = __import__(
'project.controllers.' + modname, None, None, modname
)
except Exception as e:
# Log exceptions here
# [...]
mod = getattr(mod, modname) # Get blueprint from module
app.register_blueprint(mod, url_prefix=module['url'])
我希望这能给你一些启发:)