Flask-Script

Flask-Scropt插件:为在Flask里编写额外的脚本提供了支持。这包括运行一个开发服务器,一个定制的Python命令行,用于执行初始化数据库、定时任务和其他属于web应用之外的命令行任务的脚本。

一. 使用 Flask-Script 支持命令行选项

1.安装

1
$ pip install flask-script

2.创建并运行命令行

第一步需要创建一个可以运行你脚本命令的Python模块。你可以随意命名它。我这里就以manage.py为例。

 在manage.py文件中,需要先创建一个Manager实例。Manager类会跟踪所有的命令和命令行调用的参数:

1
2
3
4
5
6
7
8
9
from flask_script import Manager
 
app = Flask(__name__)
# configure your app
 
manager = Manager(app)
 
if __name__ == "__main__":
    manager.run()

二. 添加自定义命令

创建自定义命令的三种方式:

  • 定义Command类的子类
  • 使用@command装饰器
  • 使用@option装饰器

(1) 定义Command类的子类

为了简单,我们就创建一个hello命令来输出“hello world”:

1
2
3
4
5
6
7
from flask_script import Command
 
class Hello(Command):
    "prints hello world"
 
    def run(self):
        print "hello world"

 接下来需要把命令添加到Mannager实例:

1
manager.add_command('hello', Hello())
from flask_script import Manager,Command
from flask import Flask
app = Flask(__name__)

manager = Manager(app)

class hello(Command):
    "prints hello world"
    def run(self):
        print("hello world")

manager.add_command('hello', hello())

if __name__ == "__main__":
    manager.run()
完整代码如下
在命令行运行如下命令:
(1)python manage.py hello
hello world
(2)python manage.py
usage: manage.py [-?] {hello,shell,runserver} ...

positional arguments:
  {hello,shell,runserver}
    hello               prints hello world
    shell               Runs a Python shell inside Flask application context.
    runserver           Runs the Flask development server i.e. app.run()

optional arguments:
  -?, --help            show this help message and exit

也可以通过把包含Command实例的字典作为manager.run()的参数:
manager.run({'hello' : Hello()})

(2)使用@command装饰器

 对于简单的命令,我们可以使用属于Manager实例的@command装饰器

1
2
3
4
@manager.command
def hello():
    "Just say hello"
    print("hello")

该方法创建命令的运行方式和Command类创建的运行方式相同;

python manager.py hello
> hello world

 (3)使用@option装饰器

如果需要通过命令行进行比较复杂的控制,可以使用Manager实例的@option装饰器。

--可以有多个@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

  

原文地址:https://www.cnblogs.com/zhangningyang/p/8276909.html