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