flask-script插件

Posted 向前跑,带着冷眼与嘲笑

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了flask-script插件相关的知识,希望对你有一定的参考价值。

  首先在启动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

 

以上是关于flask-script插件的主要内容,如果未能解决你的问题,请参考以下文章

Flask 第九话之插件Flask-script

flask-script插件简单使用

Flask-Script

flask扩展 -- flask-script

Flask - flask-script

Flask之flask-script 指定端口