Flask CLI to create custom commands

- Andrés Cruz

En español
Flask CLI to create custom commands

Flask CLI allows you to create custom commands to perform any operation; these commands are executed in the context of the application; to install the package, we have:

$ pip install flask-cli

We register at the app level:

my_app\__init__.py

from flask_cli import FlaskCLI
***
FlaskCLI(app)

Its use is very simple and the process is carried out based on functions:

my_app\comands\user.py

def register(app):
    @app.cli.command('mycmd')
    def mycmd():
        click.echo("Test")

Therefore, a command corresponds to a function that can have the following decorators:

  • @app.cli.command registers that our function has a new command line command; if no arguments are passed, Click will assume the function name.
  • @click.argument adds a command line argument; in our case, for username and password.

With the operation clarified, we create a new function (command) to create a user:

my_app\comands\user.py

def register(app):
    @app.cli.command('create-user')
    @click.argument('username')
    @click.argument('password')
    def create_user(username, password):

        existing_username = User.query.filter_by(username=username).first()
        if existing_username:
            click.echo( 'This username has been already taken. Try another one.')
        
        user = User(username, password)
        db.session.add(user)
        db.session.commit()
        click.echo('User {0} Added.'.format(username))

    @app.cli.command('mycmd')
    def mycmd():
        click.echo("Test")

We register at the app level:

my_app\__init__.py

from flask_cli import FlaskCLI
***
# extensions
from my_app.comands.user import register
register(app)

It is important that you register the application using the FLASK_APP environment variable or that you can use commands such as:

$ flask run

To execute the project, in such a way that in this way you have access to the context of the application and with this the possibility of executing custom commands.

Andrés Cruz

Desarrollo con Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz en Udemy

Acepto recibir anuncios de interes sobre este Blog.