Flask-Scropt插件为在Flask里编写额外的脚本提供了支持。这包括运行一个开发服务器,一个定制的Python命令行,用于执行初始化数据库、定时任务和其余属于web应用以外的命令行任务的脚本。python
使用pip来安装:web
pip install Flask-Script
示例代码以下:sql
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). 建立实例
manager = Manager(app): 先建立一个Manager实例。Manager类会跟踪全部的命令和命令行调用的参数。
2)运行命令
manager.run(): 方法初始化Manager实例来接收命令行输入。
3)建立自定义命名
建立自定义命令有三种方法:shell
from flask_script import Command class Hello(Command): "prints hello world" def run(self): print "hello world" #将命令添加到Manager实例: manager.add_command('hello', Hello())
@manager.command def hello(): "Just say hello" print("hello")
from flask_script import Manager from debug import app manager = Manager(app) @manager.option('-n', '--name', dest='name', help='Your name', default='world') #命令既能够用-n,也能够用--name,dest="name"用户输入的命令的名字做为参数传给了函数中的name @manager.option('-u', '--url', dest='url', default='www.csdn.com') #命令既能够用-u,也能够用--url,dest="url"用户输入的命令的url做为参数传给了函数中的url def hello(name, url): 'hello world or hello <setting name>' print 'hello', name print url if __name__ == '__main__': manager.run()
5). 使用
在命令行运行以下命令:数据库
$python manage.py helloflask
hello world
python manager.py hello -n sissiy -u www.sissiy.com服务器
hello sissiy
www.sissiy.com
6). 使用shell添加上下文
每次启动shell会话都要导入数据库实例和模型,这真是份枯燥的工做。为了不一直重复导入,咱们能够作些配置,让Flask-Script的shell命令自动导入特定的对象。
若想把对象添加到导入列表中,咱们要为shell命令注册一个make_context回调函数。app
from flask.ext.script import Shell def make_shell_context(): return dict(app=app, db=db, User=User, Role=Role) manager.add_command("shell", Shell(make_context=make_shell_context))
make_shell_context()函数注册了程序、数据库实例以及模型,所以这些对象能直接导入shell:函数
$ python hello.py shell >>> app <Flask 'app'> >>> db <SQLAlchemy engine='sqlite:////home/flask/flasky/data.sqlite'> >>> User <class 'app.User'>