KingFish
KingFish

Reputation: 9163

Moving Custom CLI commands to another file

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

Command Line Interface

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

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

This is what I tried:

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")

Thanks

Upvotes: 2

Views: 618

Answers (1)

Adrian Krupa
Adrian Krupa

Reputation: 1937

I would do something like this:

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)

It's common to create and configure (or just configure) app in factory functions.

Upvotes: 3

Related Questions