首先在启动Flask项目时,我们可以传不同的参数作为运行参数。但是我们只能在入口app.run()传参。这样十分的不方便。Flask-Script 是一个 Flask 扩展,为 Flask 程序添加了一个命令行解析器。 Flask-Script 自带了一组常用选项,而且还支持自定义命令。
自定义创建命令的方法有三种:
from flask import Flaskfrom flask_script import Managerfrom flask_script import Commandapp = Flask(__name__)manager = Manager(app)class Hello(Command): 'hello world' def run(self): print('hello world!')#绑定到Hello函数manager.add_command('hel', Hello())if __name__ == '__main__': manager.run()
执行
(flask_blog) jeff@debian:~/PycharmProjects/flask_blog$ python script_test.py helhello world!
第二种方法
from flask import Flaskfrom flask_script import Managerfrom flask_script import Commandapp = Flask(__name__)manager = Manager(app)#绑定到Hello函数@manager.commanddef hi(): print('hello world!')if __name__ == '__main__': manager.run()
运行
(flask_blog) jeff@debian:~/PycharmProjects/flask_blog$ python script_test.py hihello world!
当参数多个时,使用第三种方式
from flask import Flaskfrom flask_script import Managerapp = Flask(__name__)manager = Manager(app)@manager.option('-n', '--name', dest='name', help='Your name', default='world')def hi(name): 'hello world or hello' print('hello', name)if __name__ == '__main__': manager.run()
运行结果:
(flask_blog) jeff@debian:~/PycharmProjects/flask_blog$ python script_test.py hihello world(flask_blog) jeff@debian:~/PycharmProjects/flask_blog$ python script_test.py hi -n jeffhello jeff(flask_blog) jeff@debian:~/PycharmProjects/flask_blog$ python script_test.py hi --name jeffhello jeff(flask_blog) jeff@debian:~/PycharmProjects/flask_blog$ python script_test.py hi --name jeff1hello jeff1