Implementing Command-Line Interfaces in Flask with Flask-Script
Flask-Script extends Flask applications by integrating a command-line interface. It enables developers to execute external tasks directly from the terminal, such as launching development servers, running database migrations, scehduling background jobs, or invoking custom utility functions outside the standard request-response cycle.
Installation
The package can be added to a Python environment via pip:
pip install Flask-Script
Basic Integration
To enable CLI capabilities, instantiate the Manager class and bind it to the Flask application instance. The manager replaces the standard app.run() call and routes terminal input to the appropriate handlers.
from flask import Flask
from flask_script import Manager
application = Flask(__name__)
cli_manager = Manager(application)
@application.route('/')
def home():
return 'Service Online'
if __name__ == '__main__':
cli_manager.run()
Execution shifts to the terminal using the runserver subcommand:
python app_cli.py runserver
The built-in server command accepts various flags to configure the host, port, threading, and SSL certificates. For instance, binding to a specific port uses the -p flag:
python app_cli.py runserver -p 9000
Defining Simple Commands
The @manager.command decorator registers a Python function as a terminal command. It automatically maps positional arguments from the CLI to the function parameters without requiring explicit flag definitions.
@cli_manager.command
def greet():
print('System initialized successfully.')
@cli_manager.command
def repeat_message(text, count):
print((text + '\n') * int(count))
Running python app_cli.py repeat_message "Hello" 3 outputs the string three times. This approach works efficiently for straightforward utilities where argument parsing remains minimal and strictly positional.
Handling Named Arguments
When commands require named flags, optional parameters, or specific destination variables, the @manager.option decorator provides granular control. Each decerator instance defines a single CLI flag and maps it to a function parameter.
@cli_manager.option('-u', '--username', dest='user')
@cli_manager.option('-r', '--role', dest='access_level', default='viewer')
def create_account(user, access_level):
print(f'Creating account for {user} with {access_level} privileges.')
Terminal usage supports both short and long forms, allowing flexible invocation:
python app_cli.py create_account -u admin -r superuser
python app_cli.py create_account --username guest --role editor
Usage Guidelines
Select the decorator based on parameter complexity. Use @manager.command for functions that rely solely on positional inputs or require no arguments. Switch to @manager.option when implementing optional flags, default values, or explicit parameter mapping for more robust CLI tools.