一. 使用 Flask-Script 支持命令行选项
1. 安装
$ pip install flask-script
2. 配置
from flask_script import Manager
manager = Manager(app)
# ...
if __name__ == "__main__":
manager.run()
3. 使用
$ python hello.py
usage: myflask.py [-h] {shell,runserver} ...
positional arguments:
{shell,runserver}
shell Runs a Python shell inside Flask application context.
runserver Runs the Flask development server i.e. app.run()
optional arguments:
-h, --help show this help message and exit
$ python hello.py shell --help
$ python hello.py runserver --help
$ python hello.py runserver --host 0.0.0.0
二. 添加自定义命令
方法一 : manager.add_command()
使用 Flask-Script 的 shell 命令自动导入特定的对象 : 为 shell 注册一个 make_context 回调函数.
示例代码 :
from flask_script import Shell
def make_shell_conntext():
""" make_shell_context() 注册了程序, 数据库实例, 以及模型."""
return dict(app=app, db=db, User=User, Role=Role)
manager.add_command("shell". Shell(make_context=make_shell_context)) # 添加命令.
方法二 : manager.command() 装饰器
manager.command 让自定义命令变得简单. 装饰函数名就是命令名, 安徽省农户的文档字符串会显示在帮助命令中.
示例代码 :
@manager.command
def test():
"""Run the unit tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)