码迷,mamicode.com
首页 > 其他好文 > 详细

flask扩展 -- flask-script

时间:2018-01-11 22:22:30      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:src   自定义   额外   命令行   optional   需要   serve   install   python   

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

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

1.安装

$ pip install flask-script

2.创建并运行命令行

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

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

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”:

from flask_script import Command

class Hello(Command):
    "prints hello world"

    def run(self):
        print "hello world"

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

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装饰器

@manager.command
def hello():
    "Just say hello"
    print("hello")

 其使用方法和前面一样。

 (3)使用@option装饰器

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

@manager.option(‘-n‘, ‘--name‘, help=‘Your name‘)
def hello(name):
    print("hello", name)

 

flask扩展 -- flask-script

标签:src   自定义   额外   命令行   optional   需要   serve   install   python   

原文地址:https://www.cnblogs.com/shaojiafeng/p/8270305.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!