Flask-Script

Flask-Script是一个让你的命令行支持自定义命令的工具,它为Flask程序添加一个命令行解释器。可以让我们的程序从命令行直接执行相应的程序。

1、引入

from flask_script import Manager, Shell
manager = Manager(app)


if __name__ == 'main':
    manager.run()

2、创建并加入命令(引用https://www.jianshu.com/p/8148e81b42de)。
  There are three methods for creating commands,即创建Command子类、使用@command修饰符、使用@option修饰符

  1st:创建Command子类

#-*-coding:utf8-*-  
from flask_script import Manager  
from flask_script import Command  
from debug import app  
  
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()  
python manage.py hello
> hello world

  2nd:使用@command修饰符

 

  3rd:使用@option修饰符

  

3、集成Python shell

在《python web》第五章中,每次启动python shell会话都要导入数据库实例和模型,很麻烦。为了避免一直重复导入,我们可以做些配置让Flask-Script的Shell命令自动导入特定的对象。若想把对象添加到导入列表中,我们要为shell命令注册一个make_context回调函数

 

from app import create_app, db
from app.models import User, Role
from flask_script import Manager, Shell
from flask_migrate import Migrate, MigrateCommand

app = create_app('default')
manager = Manager(app)
migrate = Migrate(app, db)#数据库迁移

def make_shell_context():#回调函数
    return dict(app=app, db=db, User=User, Role=Role)
manager.add_command('shell', Shell(make_context=make_shell_context))
# 为了导出数据库迁移命令,flask_migrate提供一个MigrateCommand类,可附加到flask_script的manager对象上 manager.add_command('db', MigrateCommand) if __name__ == '__main__': manager.run()

 

 

4、使用

  python hello.py runserver --help

  python hello.py runserver --host 0.0.0.0

  python hello.py db init

  python hello.py shell #这时候已经shell里已经导入了User、Role、db,不用每次都导入了

posted @ 2020-04-01 21:45  cheng4632  阅读(150)  评论(0编辑  收藏  举报