• flask-script插件简单使用


      介绍: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

     

  • 相关阅读:
    linux命令学习笔记(53):route命令
    linux命令学习笔记(52):ifconfig命令
    linux命令学习笔记(51):lsof命令
    linux命令学习笔记(47):iostat命令
    图文并解Word插入修改删除批注
    两步教你生成文档目录
    UML 类图介绍
    win7电脑磁盘文件以分组方式展现解决方案
    jQuery插件开发中$.extend和$.fn.extend辨析
    jquery.fn.extend与jquery.extend
  • 原文地址:https://www.cnblogs.com/sxh-myblogs/p/8277584.html
Copyright © 2020-2023  润新知