Create Custom Command Line in your Flask Project

Feri Lukmansyah
Zetta Tech
Published in
2 min readMay 7, 2023
Photo by Xavier Cee on Unsplash

in this section, I will discuss the command line interface, this is my favorite topic, so let’s check out

Background

after I did a task from my client, I thought to reduce the site setup and create make simple CLI tools using Typer, I thought “How to implement using Flask?”. so after I read the documentation I found it.

for this task, I use cli a module from Flask I combinate using rich like I create CLI tools using Typer.

Project Setup

let’s start the project setup to see the implementation, is installing the required library

pip install flask rich

create manage.py if setup the project for modular code

# manage.py
from core.factory import create_app

app = create_app()

if __name__ == '__main__':
app.run()

after the create factory.py inside coreto setup Flask to a modular project

# core/factory.py
from flask import Flask

from .cli import createsuperuser

def create_app() -> Flask:
app = Flask(__name__)

# register a new command here
app.cli.add_command(createsuperuser)

return app

I need to create an independent file for a command line setup so I create cli.py inside core directory

# core/cli.py
# so we can add cli command here
# flask custom command line tools

import click
from flask.cli import with_appcontext
from rich import print


@click.command(name='createsuperuser')
@click.option('-e', '--email', required=True, type=str)
@with_appcontext
def createsuperuser(email):
"""creating flask superuser for give admin access
"""
# the logic is here
print("Creating Flask Superuser")
print(f"With Email {email}")

the example is a command to create a superuser, so we can create a superuser for Flask from the terminal to make easy the site setup.

flask createsuperuser -e="zettasoft"

the result is

Creating Flask Superuser
With Email zettasoft

Conclusion

to make an easy Flask site setup we can create command line tools for the shortcut, and make clearly documentation from there, here is a documentation for Flask custom command line and click.

you can access the source code in replit

--

--