码迷,mamicode.com
首页 > 其他好文 > 详细

flask-script插件简单使用

时间:2018-01-12 21:21:04      阅读:390      评论:0      收藏:0      [点我收藏+]

标签:web   lap   子类   ext   数据库   body   技术   rip   text   

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

  使用

  1.安装:pip install flask-script

  2.创建manager实例

技术分享图片
1 from flask_script import Manager
2  
3 app = Flask(__name__)
4 # configure your app
5  
6 manager = Manager(app)
7  
8 if __name__ == "__main__":
9     manager.run()
View Code

  3.添加自定义命令(三种方式)

 

定义Command类的子类
使用@command装饰器
使用@option装饰器

 

  a.定义command子类

 

技术分享图片
1 from flask_script import Command
2 class Hello(Command):
3     "prints hello world"
4     def run(self):
5         print "hello world"
View Code

 

  把命令添加到Mannager实例:

manager.add_command(hello, Hello())

  完整代码:

技术分享图片
 1 from flask import Flask
 2 from flask_script import Manager,Command
 3 app = Flask(__name__)
 4 manager = Manager(app)
 5 class hello(Command):
 6     "prints hello world"
 7     def run(self):
 8         print("hello world")
 9 manager.add_command(hello, hello())
10 
11 if __name__ == "__main__":
12     manager.run()
13     # manager.run({‘hello‘: hello()})
View Code
技术分享图片
 1 (1)python script.py hello
 2 hello world
 3 (2)python script.py
 4 usage: script.py [-?] {hello,shell,runserver} ...
 5 
 6 positional arguments:
 7   {hello,shell,runserver}
 8     hello               prints hello world
 9     shell               Runs a Python shell inside Flask application context.
10     runserver           Runs the Flask development server i.e. app.run()
11 
12 optional arguments:
13   -?, --help            show this help message and exit
14 
15 也可以通过把包含Command实例的字典作为manager.run()的参数
执行命令与结果

  b.使用command装饰器

 

 

 

技术分享图片
1 @manager.command
2 def hello():
3     "Just say hello"
4     print("hello")
View Code

 

  c.使用@option装饰器

 

技术分享图片
1 如果需要通过命令行进行比较复杂的控制,可以使用Manager实例的@option装饰器。
2 @manager.option(-n, --name, help=Your name)
3 def hello(name):
4     print("hello", name)
View Code

 

 

 

 

flask-script插件简单使用

标签:web   lap   子类   ext   数据库   body   技术   rip   text   

原文地址:https://www.cnblogs.com/sxh-myblogs/p/8277584.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!