I have a bunch ofcustom Flask commands in a project, added according to the docs, eg:
import click
from flask import Flask
from flask.cli import AppGroup
app = Flask(__name__)
user_cli = AppGroup('user')
@user_cli.command('create')
@click.argument('name')
def create_user(name):
...
app.cli.add_command(user_cli)
I also need to run some of the commands in a subprocess and log some information. How can I "resolve" a command given a string like 'flask user create demo'
and get the name of the command without any arguments , ie 'flask user create'
in this case? I can see that app.cli
has a resolve_command()
method but I'm not sure how to use it.
I assume Flask's CLI group is just a wrapper around the standard click cli group. As such, if you want to get the name and the command path, you can do this inside create_user
:
@user_cli.command('create')
@click.argument('name')
def create_user(name):
ctx = click.get_current_context()
print(ctx.command.name)
print(ctx.command_path)
Furthermore, to resolve a command based on the name, you can use the get_command
method available on a Context
: https://click.palletsprojects.com/en/7.x/api/#click.MultiCommand.get_command
I've also added an app
command that resolves a command, using resolve_command
. This might help you achieve what you want. What is the use case for what you're trying to achieve, if you don't mind me asking?
@app.cli.command('resolve')
@click.argument('name', nargs=-1)
def resolve(name):
group, *command = app.cli.resolve_command(click.get_current_context(), name)
print(group)
print(command)
❯ flask resolve user create
user
[<AppGroup user>, ('create',)]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.