Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I implement flask custom commands (cli)

Creating custom commands in flask needs access to the app, which is generally created in app.py like this:

import click
from flask import Flask

app = Flask(__name__)

@app.cli.command("create-user")
@click.argument("name")
def create_user(name):
    ...

However, in order not to bloat my app.py, I want to put my custom commands in a separate file e.g. commands.py, but this doesn't work because the entrypoint to my project is app.py, so I'll have to import app in commands.pyand import my commands in app.py which results in a circular import error.

How can I create custom commands in separate files ?

like image 669
m0etaz Avatar asked Jul 25 '19 13:07

m0etaz


People also ask

How do I run a command line in a flask?

Click the + (Add New Configuration) button and select Python. Give the configuration a name such as “flask run”. Click the Script path dropdown and change it to Module name, then input flask . The Parameters field is set to the CLI command to execute along with any arguments.

Which of the following methods is used to test flask CLI commands?

Testing CLI Commands Use its invoke() method to call commands in the same way they would be called from the command line. In the example above, invoking the command by name is useful because it verifies that the command was correctly registered with the app.

What is CLI flask?

Installing Flask installs the flask script, a Click command line interface, in your virtualenv. Executed from the terminal, this script gives access to built-in, extension, and application-defined commands.


1 Answers

One way to achieve this would be using blueprints

I have tested it using Flask 1.1.1, so be sure to check the documentation of the correct version that you have.

Here is the general idea:

  1. Create one or more Blueprints in a different file, let's say it's called commands.py
  2. Then import the new blueprints and register them to your app

==> app.py <==

from flask import Flask
from commands import usersbp

app = Flask(__name__)
# you MUST register the blueprint
app.register_blueprint(usersbp)

==> commands.py <==

import click
from flask import Blueprint

usersbp = Blueprint('users', __name__)

@usersbp.cli.command('create')
@click.argument('name')
def create(name):
    """ Creates a user """
    print("Create user: {}".format(name))

Upon executing flask users you should get a response like the following:

flask users
Usage: flask users [OPTIONS] COMMAND [ARGS]...

Options:
  --help  Show this message and exit.

Commands:
  create  Creates a user
like image 77
emont01 Avatar answered Sep 20 '22 21:09

emont01