Flask - flask-script

简介

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

安装

用命令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为例。

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

from flask_script import Manager
 
app = Flask(__name__)
# configure your app
 
manager = Manager(app)
 
if __name__ == "__main__":
    manager.run()

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

此时,已经可以通过命令启动项目了,如下:

python manage.py runserver

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

如需指定ip和端口:

python manage.py runserver -h 127.0.0.1 -p 8090

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

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

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

  • 定义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)

使用

python manage.py -n '赵公子'

则会输出:‘hello 赵公子’

猜你喜欢

转载自www.cnblogs.com/zhaohuhu/p/9216106.html