Flask Script扩展提供向Flask插入外部脚本的功能,包括运行一个开发用的服务器,一个定制的Python shell,设置数据库的脚本,cronjobs,及其他运行在web应用之外的命令行任务;使得脚本和系统分开;

  Flask Script和Flask本身的工作方式类似,只需定义和添加从命令行中被Manager实例调用的命令;

官方文档:http://flask-script.readthedocs.io/en/latest/

 

1 创建并运行命令

首先,创建一个Python模板运行命令脚本,可起名为manager.py;

在该文件中,必须有一个Manager实例,Manager类追踪所有在命令行中调用的命令和处理过程的调用运行情况;

Manager只有一个参数——Flask实例,也可以是一个函数或其他的返回Flask实例;

调用manager.run()启动Manager实例接收命令行中的命令;

#-*-coding:utf8-*-  
from flask_script import Manager  
from debug import app  
  
manager = Manager(app)  
  
if __name__ == '__main__':  
    manager.run() 

其次,创建并加入命令;

三中创建命令的方式:创建Command子类、使用@command修饰符、使用@option修饰符

一、创建Command子类

Command子类必须定义一个run方法

举例:创建Hello命令,并将Hello命令加入Manager实例

from flask_script import Manager  ,Server
from flask_script import Command  
from debug import app  
  
manager = Manager(app)  


class Hello(Command):  
    'hello world'  
    def run(self):  
        print 'hello world'  

#自定义命令一:
manager.add_command('hello', Hello())  
# 自定义命令二:

manager.add_command("runserver", Server()) #命令是runserver
if __name__ == '__main__':  
    manager.run()  



"""
执行如下命令:

python manager.py hello
> hello world

 python manager.py runserver 
> hello world"""
View Code

相关文章:

猜你喜欢
  • 2018-06-22
  • 2021-10-28
  • 2022-12-23
  • 2022-01-23
相关资源
相似解决方案