1.0 Flask-Script的作用
flask-script的作用是通过命令的模式操作Flask,要使用flask-script,可以通过:
pip install flask-script 安装
from flask_script import Manager
manager = Manager(app)
@manager.command
def hello():
print('hello')
if __name__ == 'main':
manager.run()
我们把脚本命令代码放在一个叫manager.py文件中,然后直接在终端运行
1.在运行中输入cmd
2.进入虚拟环境运行下方命令
python manager.py hello
可以直接打印结果 hello
2.0 定义命令的三种方法
2.1 使用@command装饰器
2.2 使用类继承自Command类
from flask_script import Command,Manager
from your_app import app
manager = Manager(app)
class Hello(Command):
"""prints hello word """
def run(self):
print("hello word")
manager.add_command('hello',Hello())
使用类的方式,有三点需要注意
- 必须继承自Command基类
- 必须实现run方法
- 必须通过add_command方法添加命令
2.3 使用option装饰器
如果想要在使用命令的时候还传递参数进去,那么使用@option装饰器更加方便
@manager.ontion('-n','--name',desc = 'name')
def hello(name):
print('hello',name)
这样调用hello命令
python manager.py -n juran
或
python manager.py --name juran
3.0 添加参数到命令中
- option装饰器:以上三种创建命令的方式都可以添加参数
@manager.option('-n','--name',dest='name',default='joe')
@manager.option('-u','--url',dest='url',default=None)
def hello(name,url):
if url is None:
print("hello",name)
else:
print("hello",name,"form",url)
- command装饰器: command装饰器也可以添加参数,但是不那么灵活
@manager.command
def hello(name='Fred'):
print("hello",name)
- 类继承:类继承也可以添加参数
from flask_Flask import Comman,Manager,option
class Hello(Command):
option_list = (
Option('--name','-n',dest='name')
)
def run(self,name):
print("hello %s" %name)
如果要在指定参数的时候,动态的做一些事,可以使用get_options方法
class Hello(Command):
def __init__(self,default_name='joe'):
self.default_name = default_name
def get_options(self):
return [
Option('-n','--name',dest='name',default=self.default_name)
]
def run(self,name):
print('hello',name)