简介
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 赵公子'
来源: http://www.bubuko.com/infodetail-2655531.html