Flask之flask-script

简介

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

安装

用命令pip和easy_install安装:

pip install Flask-Script

从github下载最新版本,源码编译安装:

git clone https://github.com/smurfix/flask-script.git
cd flask-script
python setup.py develop

建立并运行命令行

第一步:实例化manage对象

须要建立一个能够运行你脚本命令的Python模块。你能够随意命名它。我这里就以manage.py为例。git

 在manage.py文件中,须要先建立一个Manager实例。Manager类会跟踪全部的命令和命令行调用的参数:github

from flask_script import Manager

app = Flask(__name__)
# configure your app

manager = Manager(app)

if __name__ == "__main__":
    manager.run()

调用manager.run()方法初始化Mnager实例来接收命令行输入。web

此时,已经能够经过命令启动项目了,以下:shell

python manage.py runserver

项目会以:Running on http://127.0.0.1:5000/ 的方式启动,数据库

如需指定ip和端口:flask

python manage.py runserver -h 127.0.0.1 -p 8090

项目则会以:Running on http://127.0.0.1:8090/ 的方式启动,其实也是能够指定IP的,只是本质也是127.0.0.1服务器

第二步:建立添加自定义命令

建立自定义命令有三种方法:app

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

(1) 定义Command类的子类ide

为了简单,咱们就建立一个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)

使用

python manage.py -n '付勇'

  则会输出:‘hello 付勇’

相关文章
相关标签/搜索