Skip to content

Extension commands¤

Overview of all classes, functions, and other objects related to defining extension commands.

Read more on Extensions.

CommandArg dataclass ¤

CommandArg(
    name_or_flags: Union[str, Sequence[str]],
    action: Optional[Union[CommandLiteralAction, Action]] = None,
    nargs: Optional[Union[int, Literal["*", "+", "?"]]] = None,
    const: Any = None,
    default: Any = None,
    type: Optional[Union[Type, Callable[[str], Any]]] = None,
    choices: Optional[Sequence[Any]] = None,
    required: Optional[bool] = None,
    help: Optional[str] = None,
    metavar: Optional[str] = None,
    dest: Optional[str] = None,
    version: Optional[str] = None,
    deprecated: Optional[bool] = None,
)

Bases: object

See source code

Define a single positional argument or an option for a command.

Fields on this class correspond to the arguments for ArgumentParser.add_argument()

Methods:

Attributes:

action class-attribute instance-attribute ¤

See source code

The basic type of action to be taken when this argument is encountered at the command line.

choices class-attribute instance-attribute ¤

choices: Optional[Sequence[Any]] = None

See source code

A sequence of the allowable values for the argument.

const class-attribute instance-attribute ¤

const: Any = None

See source code

A constant value required by some action and nargs selections.

default class-attribute instance-attribute ¤

default: Any = None

See source code

The value produced if the argument is absent from the command line and if it is absent from the namespace object.

deprecated class-attribute instance-attribute ¤

deprecated: Optional[bool] = None

See source code

Whether or not use of the argument is deprecated.

NOTE: This is supported only in Python 3.13+

dest class-attribute instance-attribute ¤

dest: Optional[str] = None

See source code

The name of the attribute to be added to the object returned by parse_args().

help class-attribute instance-attribute ¤

help: Optional[str] = None

See source code

A brief description of what the argument does.

metavar class-attribute instance-attribute ¤

metavar: Optional[str] = None

See source code

A name for the argument in usage messages.

name_or_flags instance-attribute ¤

name_or_flags: Union[str, Sequence[str]]

See source code

Either a name or a list of option strings, e.g. 'foo' or '-f', '--foo'.

nargs class-attribute instance-attribute ¤

nargs: Optional[Union[int, Literal['*', '+', '?']]] = None

See source code

The number of command-line arguments that should be consumed.

required class-attribute instance-attribute ¤

required: Optional[bool] = None

See source code

Whether or not the command-line option may be omitted (optionals only).

type class-attribute instance-attribute ¤

type: Optional[Union[Type, Callable[[str], Any]]] = None

See source code

The type to which the command-line argument should be converted.

version class-attribute instance-attribute ¤

version: Optional[str] = None

See source code

The version string to be added to the object returned by parse_args().

MUST be used with action='version'.

See https://docs.python.org/3/library/argparse.html#action

asdict ¤

asdict() -> dict

See source code

Convert the dataclass to a dictionary, stripping out fields with None values

CommandArgGroup dataclass ¤

CommandArgGroup(title: Optional[str] = None, description: Optional[str] = None, arguments: Sequence[CommandArg] = ())

Bases: object

See source code

Define a group of arguments for a command.

Fields on this class correspond to the arguments for ArgumentParser.add_argument_group()

Methods:

Attributes:

arguments class-attribute instance-attribute ¤

arguments: Sequence[CommandArg] = ()

description class-attribute instance-attribute ¤

description: Optional[str] = None

See source code

Description for the argument group in help output, by default None

title class-attribute instance-attribute ¤

title: Optional[str] = None

See source code

Title for the argument group in help output; by default “positional arguments” if description is provided, otherwise uses title for positional arguments.

asdict ¤

asdict() -> dict

See source code

Convert the dataclass to a dictionary, stripping out fields with None values

CommandHandler ¤

CommandParserInput dataclass ¤

CommandParserInput(
    prog: Optional[str] = None,
    usage: Optional[str] = None,
    description: Optional[str] = None,
    epilog: Optional[str] = None,
    parents: Optional[Sequence[ArgumentParser]] = None,
    formatter_class: Optional[Type[_FormatterClass]] = None,
    prefix_chars: Optional[str] = None,
    fromfile_prefix_chars: Optional[str] = None,
    argument_default: Optional[Any] = None,
    conflict_handler: Optional[str] = None,
    add_help: Optional[bool] = None,
    allow_abbrev: Optional[bool] = None,
    exit_on_error: Optional[bool] = None,
)

Bases: object

See source code

Typing for the input to the ArgumentParser constructor.

Methods:

Attributes:

add_help class-attribute instance-attribute ¤

add_help: Optional[bool] = None

See source code

Add a -h/--help option to the parser (default: True)

allow_abbrev class-attribute instance-attribute ¤

allow_abbrev: Optional[bool] = None

See source code

Allows long options to be abbreviated if the abbreviation is unambiguous. (default: True)

argument_default class-attribute instance-attribute ¤

argument_default: Optional[Any] = None

See source code

The global default value for arguments (default: None)

conflict_handler class-attribute instance-attribute ¤

conflict_handler: Optional[str] = None

See source code

The strategy for resolving conflicting optionals (usually unnecessary)

description class-attribute instance-attribute ¤

description: Optional[str] = None

See source code

Text to display before the argument help (by default, no text)

epilog class-attribute instance-attribute ¤

epilog: Optional[str] = None

See source code

Text to display after the argument help (by default, no text)

exit_on_error class-attribute instance-attribute ¤

exit_on_error: Optional[bool] = None

See source code

Determines whether or not ArgumentParser exits with error info when an error occurs. (default: True)

formatter_class class-attribute instance-attribute ¤

formatter_class: Optional[Type[_FormatterClass]] = None

See source code

A class for customizing the help output

fromfile_prefix_chars class-attribute instance-attribute ¤

fromfile_prefix_chars: Optional[str] = None

See source code

The set of characters that prefix files from which additional arguments should be read (default: None)

parents class-attribute instance-attribute ¤

parents: Optional[Sequence[ArgumentParser]] = None

See source code

A list of ArgumentParser objects whose arguments should also be included

prefix_chars class-attribute instance-attribute ¤

prefix_chars: Optional[str] = None

See source code

The set of characters that prefix optional arguments (default: ‘-‘)

prog class-attribute instance-attribute ¤

prog: Optional[str] = None

See source code

The name of the program (default: os.path.basename(sys.argv[0]))

usage class-attribute instance-attribute ¤

usage: Optional[str] = None

See source code

The string describing the program usage (default: generated from arguments added to parser)

asdict ¤

asdict() -> dict

See source code

Convert the dataclass to a dictionary, stripping out fields with None values

CommandSubcommand dataclass ¤

CommandSubcommand(
    title: Optional[str] = None,
    description: Optional[str] = None,
    prog: Optional[str] = None,
    parser_class: Optional[Type[ArgumentParser]] = None,
    action: Optional[Union[CommandLiteralAction, Action]] = None,
    dest: Optional[str] = None,
    required: Optional[bool] = None,
    help: Optional[str] = None,
    metavar: Optional[str] = None,
)

Bases: object

See source code

Define a subcommand for a command.

Fields on this class correspond to the arguments for ArgumentParser.add_subparsers.add_parser()

Methods:

Attributes:

action class-attribute instance-attribute ¤

See source code

The basic type of action to be taken when this argument is encountered at the command line.

description class-attribute instance-attribute ¤

description: Optional[str] = None

See source code

Description for the sub-parser group in help output, by default None.

dest class-attribute instance-attribute ¤

dest: Optional[str] = None

See source code

Name of the attribute under which sub-command name will be stored; by default None and no value is stored.

help class-attribute instance-attribute ¤

help: Optional[str] = None

See source code

Help for sub-parser group in help output, by default None.

metavar class-attribute instance-attribute ¤

metavar: Optional[str] = None

See source code

String presenting available subcommands in help; by default it is None and presents subcommands in form {cmd1, cmd2, ..}.

parser_class class-attribute instance-attribute ¤

parser_class: Optional[Type[ArgumentParser]] = None

See source code

Class which will be used to create sub-parser instances, by default the class of the current parser (e.g. ArgumentParser).

prog class-attribute instance-attribute ¤

prog: Optional[str] = None

See source code

Usage information that will be displayed with sub-command help, by default the name of the program and any positional arguments before the subparser argument.

required class-attribute instance-attribute ¤

required: Optional[bool] = None

See source code

Whether or not a subcommand must be provided, by default False (added in 3.7)

title class-attribute instance-attribute ¤

title: Optional[str] = None

See source code

Title for the sub-parser group in help output; by default “subcommands” if description is provided, otherwise uses title for positional arguments.

asdict ¤

asdict() -> dict

See source code

Convert the dataclass to a dictionary, stripping out fields with None values

ComponentCommand ¤

Bases: object

See source code

Definition of a CLI command.

This class is based on Python's argparse module and Django's BaseCommand class. ComponentCommand allows you to define:

  • Command name, description, and help text
  • Arguments and options (e.g. --name John)
  • Group arguments (see argparse groups)
  • Subcommands (e.g. components ext run my_ext hello)
  • Handler behavior

Each extension can add its own commands, which will be available to run with components ext run.

Extensions use the ComponentCommand class to define their commands.

For example, if you define and install the following extension:

from django_components ComponentCommand, ComponentExtension

class HelloCommand(ComponentCommand):
    name = "hello"
    help = "Say hello"
    def handle(self, *args, **kwargs):
        print("Hello, world!")

class MyExt(ComponentExtension):
    name = "my_ext"
    commands = [HelloCommand]

You can run the hello command with:

python manage.py components ext run my_ext hello

You can also define arguments for the command, which will be passed to the command's handle method.

from django_components import CommandArg, ComponentCommand, ComponentExtension

class HelloCommand(ComponentCommand):
    name = "hello"
    help = "Say hello"
    arguments = [
        CommandArg(name="name", help="The name to say hello to"),
        CommandArg(name=["--shout", "-s"], action="store_true"),
    ]

    def handle(self, name: str, *args, **kwargs):
        shout = kwargs.get("shout", False)
        msg = f"Hello, {name}!"
        if shout:
            msg = msg.upper()
        print(msg)

You can run the command with:

python manage.py components ext run my_ext hello --name John --shout

Note

Command arguments and options are based on Python's argparse module.

For more information, see the argparse documentation.

Attributes:

arguments class-attribute instance-attribute ¤

See source code

argparse arguments for the command

handle class-attribute instance-attribute ¤

handle: Optional[CommandHandler] = None

See source code

The function that is called when the command is run. If None, the command will print the help message.

help class-attribute instance-attribute ¤

help: Optional[str] = None

See source code

The help text for the command

name instance-attribute ¤

name: str

See source code

The name of the command - this is what is used to call the command

parser_input class-attribute instance-attribute ¤

parser_input: Optional[CommandParserInput] = None

See source code

The input to use when creating the ArgumentParser for this command. If None, the default values will be used.

subcommands class-attribute instance-attribute ¤

subcommands: Sequence[Type[ComponentCommand]] = ()

See source code

Subcommands for the command

subparser_input class-attribute instance-attribute ¤

subparser_input: Optional[CommandSubcommand] = None

See source code

The input to use when this command is a subcommand installed with add_subparser(). If None, the default values will be used.