zoukankan      html  css  js  c++  java
  • flask扩展 -- flask-script

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

    一. 使用 Flask-Script 支持命令行选项

    1.安装

    $ pip install flask-script
    

    2.创建并运行命令行

    第一步需要创建一个可以运行你脚本命令的Python模块。你可以随意命名它。我这里就以manage.py为例。

     在manage.py文件中,需要先创建一个Manager实例。Manager类会跟踪所有的命令和命令行调用的参数:

    from flask_script import Manager
    
    app = Flask(__name__)
    # configure your app
    
    manager = Manager(app)
    
    if __name__ == "__main__":
        manager.run()
    

    二. 添加自定义命令

    创建自定义命令的三种方式:

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

    (1) 定义Command类的子类

    为了简单,我们就创建一个hello命令来输出“hello world”:

    from flask_script import Command
    
    class Hello(Command):
        "prints hello world"
    
        def run(self):
            print "hello world"
    

     接下来需要把命令添加到Mannager实例:

    manager.add_command('hello', Hello())
    
    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)python manage.py hello
    hello world
    (2)python manage.py
    usage: manage.py [-?] {hello,shell,runserver} ...
    
    positional arguments:
      {hello,shell,runserver}
        hello               prints hello world
        shell               Runs a Python shell inside Flask application context.
        runserver           Runs the Flask development server i.e. app.run()
    
    optional arguments:
      -?, --help            show this help message and exit
    
    也可以通过把包含Command实例的字典作为manager.run()的参数:
    manager.run({'hello' : Hello()})

    (2)使用@command装饰器

     对于简单的命令,我们可以使用属于Manager实例的@command装饰器

    @manager.command
    def hello():
        "Just say hello"
        print("hello")
    

     其使用方法和前面一样。

     (3)使用@option装饰器

    如何需要通过命令行进行比较复杂的控制,可以使用Manager实例的@option装饰器。

    @manager.option('-n', '--name', help='Your name')
    def hello(name):
        print("hello", name)
    
  • 相关阅读:
    Dockerfile构建
    ElasticSearch学习之集成客户端
    区块链学习之Hyperledger Fabric开发环境搭建(Go+Docker+Fabric)
    区块链学习之什么是区块链(基础入门)
    python学习之多版本管理及Python安装/卸载遇到的坑(MAC版)
    ElasticSearch学习之基本原理概述
    ElasticSearch学习之基本概念及单机/集群部署
    Kafka学习之Kafka选举机制简述
    Kafka学习之内核原理剖析
    通过idea将java项目发布到harbor仓库
  • 原文地址:https://www.cnblogs.com/shaojiafeng/p/8270305.html
Copyright © 2011-2022 走看看