将自定义CLI命令移动到另一个文件 [英] Moving Custom CLI commands to another file

查看:58
本文介绍了将自定义CLI命令移动到另一个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些针对正在编写的Flask应用程序的自定义cli命令.我正在按照这里的说明进行操作:

I have a few custom cli commands for a flask app I'm writing. I'm following the instructions here:

命令行界面

问题是我不想将它们全部放入我的app.py文件中,它会变得过分膨胀.我想做的是拥有我的项目结构:

The problem is I do not want to put them all in my app.py file, it will get overbloated. What I would like to do is have my project structure:

project
  |_ app.py
  |_ cli.py

我曾考虑过使用蓝图,但是却收到蓝图没有属性'cli'"

I thought about using a blueprint, but I get "Blueprint has no attribute 'cli'"

这是我尝试过的:

cli = Blueprint('cli', __name__)  # I knew this would not work but I had to try

@cli.cli.command()
@click.argument('name')
def create_user(name):
    print("hello")

谢谢

推荐答案

我会做这样的事情:

cli.py:

from flask import Flask
import click

def register_cli(app: Flask):
    @app.cli.command()
    @click.argument('name')
    def create_user(name):
        print("hello", name)

app.py:

from flask import Flask
from cli import register_cli

app = Flask(__name__)
register_cli(app)

查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆