Ci-dessous, les différences entre deux révisions de la page.
| Les deux révisions précédentesRévision précédenteProchaine révision | Révision précédente | ||
| dev:python:flask:definir_commande_cli [2026/04/05 10:39] – yoann | dev:python:flask:definir_commande_cli [2026/04/05 12:55] (Version actuelle) – yoann | ||
|---|---|---|---|
| Ligne 1: | Ligne 1: | ||
| {{tag> | {{tag> | ||
| - | |||
| - | : | ||
| ====== Flask : Définir une commande CLI ====== | ====== Flask : Définir une commande CLI ====== | ||
| Ligne 21: | Ligne 19: | ||
| </ | </ | ||
| - | La commande '' | + | La commande '' |
| <code bash> | <code bash> | ||
| Ligne 28: | Ligne 26: | ||
| + | ===== Groupes de commandes ===== | ||
| + | |||
| + | Il est possible d' | ||
| + | |||
| + | On peut par exemple créer un groupe '' | ||
| + | |||
| + | <code python> | ||
| + | import click | ||
| + | from flask import Flask | ||
| + | from flask.cli import AppGroup | ||
| + | |||
| + | app = Flask(__name__) | ||
| + | user_commands = AppGroup(' | ||
| + | |||
| + | @user_commands.command(' | ||
| + | @click.argument(' | ||
| + | def create_user(name): | ||
| + | """ | ||
| + | click.echo(f" | ||
| + | |||
| + | @user_commands.command(' | ||
| + | @click.argument(' | ||
| + | def delete_user(name): | ||
| + | """ | ||
| + | click.echo(f" | ||
| + | |||
| + | app.cli.add_command(user_commands) | ||
| + | </ | ||
| + | |||
| + | ===== Utilisation avec les Blueprints ===== | ||
| + | |||
| + | Si l' | ||
| + | |||
| + | <code python cli.py> | ||
| + | """ | ||
| + | Blueprint regroupant les commandes CLI globales pour l' | ||
| + | """ | ||
| + | |||
| + | from flask import Blueprint | ||
| + | from app.config import DefaultConfig | ||
| + | import click | ||
| + | |||
| + | cmd_bp = Blueprint( ' | ||
| + | |||
| + | @cmd_bp.cli.command(' | ||
| + | def version(): | ||
| + | """ | ||
| + | click.echo(f" | ||
| + | </ | ||
| + | |||
| + | Ici, lors de l' | ||
| + | |||
| + | Ensuite, dans l' | ||
| + | <code python> | ||
| + | from flask import Flask | ||
| + | from app.cli import cmd_bp | ||
| + | |||
| + | # Charge les classes de configuration | ||
| + | from app.config import DevelopmentConfig | ||
| + | |||
| + | |||
| + | def create_app() -> Flask: | ||
| + | app = Flask(__name__) | ||
| + | app.config.from_object(DevelopmentConfig) | ||
| + | |||
| + | ... | ||
| + | |||
| + | app.register_blueprint(cmd_bp) | ||
| + | |||
| + | return app | ||
| + | </ | ||
| + | |||
| + | |||
| + | ===== Arguments et options ===== | ||
| + | |||
| + | La documentation officielle du package Click détaille la [[https:// | ||
| + | |||
| + | |||
| ===== Références ===== | ===== Références ===== | ||
| * [[https:// | * [[https:// | ||
| * [[https:// | * [[https:// | ||