在 Flask 0.11 版本的 ChangLog 中我们可以发现里面有一条是引入了 click 模块用于在开发服务器启动 Flask,而且人家可是明确得说要替换 Flask-Script:

Added flask and the flask.cli module to start the local debug server through the click CLI system. This is recommended over the old flask.run() method as it works faster and more reliable due to a different design and also replaces Flask-Script.

感觉 Flask 在某些程度上来说,有些东西是非常值得吐槽,例如一直以来被吐槽的 jinja 模板绑定,作为一个 web 框架,模板可以说没必要绑定死吧,而且替换的方式也不是很方便,而且还有这个启动的库,也没有必要加载框架里面吧,所以说是需要吐槽的。但是,作为一款流行的框架,Flask 值得赞赏的地方还是很多的,例如 Blueprint/Route/Extension 等之类的,所以既然框架内提供了,不妨看一下如何好好利用好它。

那么,我们想看下 click 的官方介绍,看下它自身觉得值得自豪的特性有哪些,在 click 的官方介绍中,它自诩的特性有:

那这里就看一下 click 的如何实现这些特性的:

嵌套命令

在 Flask-Script,我们可能经常使用的方式是:

1
python manage.py runserver

这是简单的命令,也就是只有一个命令,但是,如果你使用过 Flask-SQLAlchemy 的话,应该知道有一些命令是需要多个命令的,例如:

1
2
python manage.py db init
python manage.py db migrate

这里就是所谓的嵌套命令,我们看一下在 click 中如何实现:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# test.py
@click.group()
def cli():
    pass

@cli.command()
def initdb():
    click.echo('Initialized the database')

@cli.command()
def dropdb():
    click.echo('Dropped the database')

这里是有一个 group 的概念,对于这个情况,我们使用的命令就是:

1
2
python test.py cli initdb
python test.py cli dropdb

自动生成 help

在使用 Flask-Script 的时候,有一个很有用的功能就是有命令帮助提示,同时 click 也会有这种功能,对于我们刚才的 test.py,我们可以直接使用 --help,就可以看到提示了:

1
2
3
4
5
6
7
8
9
$ python test.py --help
Usage: test.py [OPTIONS] COMMAND [ARGS]...

Options:
  --help  Show this message and exit.

Commands:
  dropdb
  initdb

Click

因为 Click 的整体特性太多,一一讲述太浪费了,而且也没有什么必要,这里就介绍一些常见的例子,作为后面的工作需要进行使用,对于一些毕竟偏门的特性,等我以后用到的时候再补充好了。

参数设置

命令的参数正常情况下都必不可少,在 click 中,有两种参数一种是 option,另一种是 argument,option 的功能比 argument 强大,但是 argument 是有顺序的,也就是不能乱序。

在 click 中使用 option 和 Flask-Script 没有太大区别,而且到最后进行 help 显示的时候也是差不多的,但是 click 是支持类型的,也就是说有 INT、STRING 的区别,这里举个例子:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#!/usr/bin/env python
# encoding: utf-8
import click

import sys

@click.command()
@click.option('--upper', 'transformation', flag_value='upper',
              default=True)
@click.option('--lower', 'transformation', flag_value='lower')
def info(transformation):
    click.echo(getattr(sys.platform, transformation)())

if __name__ == "__main__":
    info()

使用 --help 就可以看到帮助信息了:

1
2
3
4
5
6
7
$ python test.py --help 
Usage: test.py [OPTIONS]

Options:
  --upper
  --lower
  --help   Show this message and exit.