1. 程式人生 > >flask-script插件

flask-script插件

是我 令行 創建 綁定 常用選項 font span body 函數

  首先在啟動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) jeff@debian:~/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) jeff@debian:~/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) jeff@debian:~/PycharmProjects/flask_blog$ python script_test.py hi
hello world
(flask_blog) jeff@debian:~/PycharmProjects/flask_blog$ python script_test.py hi -n jeff
hello jeff
(flask_blog) jeff@debian:~/PycharmProjects/flask_blog$ python script_test.py hi --name jeff
hello jeff
(flask_blog) jeff@debian:~/PycharmProjects/flask_blog$ python script_test.py hi --name jeff1
hello jeff1

flask-script插件