Theme
Version
GitHubPyPIDiscord
On this page

Extension commands

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

Read more on Extensions.

CommandArg

CommandArg(
    name_or_flags: str | Sequence[str],
    action: CommandLiteralAction | Action | None = None,
    nargs: int | Literal['*', '+', '?'] | None = None,
    const: Any = None,
    default: Any = None,
    type: type | Callable[[str], Any] | None = None,
    choices: Sequence[Any] | None = None,
    required: bool | None = None,
    help: str | None = None,
    metavar: str | None = None,
    dest: str | None = None,
    version: str | None = None,
    deprecated: bool | None = 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()

Attributes

name_or_flags

name_or_flags: str | Sequence[str]

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

action

action: CommandLiteralAction | Action | None

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

nargs

nargs: int | Literal['*', '+', '?'] | None

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

const

const: Any

A constant value required by some action and nargs selections.

default

default: Any

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

type

type: type | Callable[[str], Any] | None

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

choices

choices: Sequence[Any] | None

A sequence of the allowable values for the argument.

required

required: bool | None

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

help

help: str | None

A brief description of what the argument does.

metavar

metavar: str | None

A name for the argument in usage messages.

dest

dest: str | None

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

version

version: str | None

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

deprecated

deprecated: bool | None

Whether or not use of the argument is deprecated.

NOTE: This is supported only in Python 3.13+

Methods

asdict

asdict() -> dict

See source code

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

CommandArgGroup

CommandArgGroup(
    title: str | None = None,
    description: str | None = 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()

Attributes

title

title: str | None

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

description

description: str | None

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

Methods

asdict

asdict() -> dict

See source code

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

CommandHandler

CommandHandler()

CommandParserInput

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

Bases: object

See source code

Typing for the input to the ArgumentParser constructor.

Attributes

prog

prog: str | None

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

usage

usage: str | None

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

description

description: str | None

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

epilog

epilog: str | None

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

parents

parents: Sequence[ArgumentParser] | None

A list of ArgumentParser objects whose arguments should also be included

formatter_class

formatter_class: type[_FormatterClass] | None

A class for customizing the help output

prefix_chars

prefix_chars: str | None

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

fromfile_prefix_chars

fromfile_prefix_chars: str | None

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

argument_default

argument_default: Any | None

The global default value for arguments (default: None)

conflict_handler

conflict_handler: str | None

The strategy for resolving conflicting optionals (usually unnecessary)

add_help

add_help: bool | None

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

allow_abbrev

allow_abbrev: bool | None

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

exit_on_error

exit_on_error: bool | None

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

Methods

asdict

asdict() -> dict

See source code

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

CommandSubcommand

CommandSubcommand(
    title: str | None = None,
    description: str | None = None,
    prog: str | None = None,
    parser_class: type[ArgumentParser] | None = None,
    action: CommandLiteralAction | Action | None = None,
    dest: str | None = None,
    required: bool | None = None,
    help: str | None = None,
    metavar: str | None = 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()

Attributes

title

title: str | None

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

description

description: str | None

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

prog

prog: str | None

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.

parser_class

parser_class: type[ArgumentParser] | None

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

action

action: CommandLiteralAction | Action | None

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

dest

dest: str | None

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

required

required: bool | None

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

help

help: str | None

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

metavar

metavar: str | None

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

Methods

asdict

asdict() -> dict

See source code

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

ComponentCommand

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

name

name: str

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

help

help: str | None

The help text for the command

arguments

argparse arguments for the command

subcommands

Subcommands for the command

handle

handle: CommandHandler | None

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

parser_input

parser_input: CommandParserInput | None

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

subparser_input

subparser_input: CommandSubcommand | None

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

django-components version: 0.152.0