参考文章https://flask-script.readthedocs.io/en/latest/
概念
Flask_script是一种Flask的交互式命令行工具。方便交互式调试、执行脚本。也就是方便以命令行的方式直接在终端中调试每个文件中的某个函数,一般有一下三种方法
方法一 创建Command子类
from flask_script import Manager,Server,Command
from flask import Flask
app=Flask(__name__)
manager=Manager(app)
class Hello(Command):
'hello world'
def run(sellf):
print("hello world")
manager.add_command('hello',Hello())
manager.add_command("runserver",Server())
if __name__=='__main__':
manager.run()
>>python demo1.py hello
>>hello world
python demo1.py runserver
* Serving Flask app "demo1" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
runserver就是相当于app.run()
方法二 使用Command实例的@command符号
from flask_script import Manager,Server,Command
from flask import Flask
app=Flask(__name__)
manager=Manager(app)
@manager.command
def hello():
'hello world'
print('hello world')
if __name__=='__main__':
manager.run()
方法三 使用Command实例的@option修饰符
from flask_script import Manager
from debug import app
manager = Manager(app)
@manager.option('-n', '--name', dest='name', help='Your name', default='world') #命令既可以用-n,也可以用--name,dest="name"用户输入的命令的名字作为参数传给了函数中的name
@manager.option('-u', '--url', dest='url', default='www.csdn.com') #命令既可以用-u,也可以用--url,dest="url"用户输入的命令的url作为参数传给了函数中的url
def hello(name, url):
'hello world or hello <setting name>'
print 'hello', name
print url
if __name__ == '__main__':
manager.run()
运行方式如下:
python manager.py hello
>hello world
>www.csdn.com
python manager.py hello -n sissiy -u www.sissiy.com
> hello sissiy
>www.sissiy.com
python manager.py hello -name sissiy -url www.sissiy.com
> hello sissiy
>www.sissiy.com