Management¶
- class django_typer.management.TyperCommand(stdout=None, stderr=None, no_color=False, force_color=False, **kwargs)[source]¶
An extension of
BaseCommand
that uses the Typer library to parse arguments and options. This class adaptsBaseCommand
using a light touch that relies on most of the originalBaseCommand
implementation to handle default arguments and behaviors.All of the documented
BaseCommand
functionality works as expected.call_command()
also works as expected. TyperCommands however add a few extra features:We define arguments and options using concise and optionally annotated type hints.
Simple TyperCommands implemented only using
handle()
can be called directly by invoking the command as a callable.We can define arbitrarily complex subcommand group hierarchies using the
group()
andcommand()
decorators.Commands and subcommands can be fetched and invoked directly as functions using
get_command()
We can define common initialization logic for groups of commands using
initialize()
TyperCommands may safely return non-string values from
handle()
Defining a typer command is a lot like defining a
BaseCommand
except that we do not have anadd_arguments()
method. Instead we define the parameters using type hints directly onhandle()
:import typing as t from django_typer import TyperCommand class Command(TyperCommand): def handle( self, arg: str, option: t.Optional[str] = None ): # do command logic here
TyperCommands can be extremely simple like above, or we can create really complex command group hierarchies with subcommands and subgroups (see
group()
andcommand()
).Typer apps can be configured with a number of parameters to control behavior such as exception behavior, help output, help markup interpretation, result processing and execution flow. These parameters can be passed to typer as keyword arguments in your Command class inheritance:
management/commands/chain.py¶1import typing as t 2from django_typer import TyperCommand, command 3 4 5class Command(TyperCommand, rich_markup_mode='markdown', chain=True): 6 7 suppressed_base_arguments = [ 8 '--verbosity', '--traceback', '--no-color', '--force-color', 9 '--skip_checks', '--settings', '--pythonpath', '--version' 10 ] 11 12 @command() 13 def command1(self, option: t.Optional[str] = None): 14 """This is a *markdown* help string""" 15 print('command1') 16 return option 17 18 @command() 19 def command2(self, option: t.Optional[str] = None): 20 """This is a *markdown* help string""" 21 print('command2') 22 return option
We’re doing a number of things here:
Using the
command()
decorator to define multiple subcommands.Using
suppressed_base_arguments
to suppress the default options Django adds to the command interface.Using rich_markup_mode to enable markdown rendering in help output.
Using the chain parameter to enable Multi Command Chaining.
We can see that our help renders like so:
chain Usage: ./manage.py chain [OPTIONS] COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]... ╭─ Options ─────────────────────────────────────────────────────────────────── ─╮ │ - -help Show this message and exit. │ ╰──────────────────────────────────────────────────────────────────────────────╯ ╭─ Django ──────────────────────────────────────────────────────────────────── ─╮ │ - -show -locals Print local variables in tracebacks. │ ╰──────────────────────────────────────────────────────────────────────────────╯ ╭─ Commands ────────────────────────────────────────────────────────────────── ─╮ │ command1 This is a markdown help string │ │ command2 This is a markdown help string │ ╰──────────────────────────────────────────────────────────────────────────────╯ And we can see the chain behavior by calling our command(s) like so:
$ ./manage.py chain command1 --option one command2 --option two command1 command2 ['one', 'two']
See
TyperCommandMeta
for the list of accepted parameters. Also refer to the Typer docs for more information on the behaviors expected for those parameters - they are passed through to the Typer class constructor. Not all parameters may make sense in the context of a django command.- Parameters:
- __call__(*args, **kwargs)[source]¶
Call this command’s derived class
handle()
implementation directly. Note this does not call thehandle()
function below - but thehandle()
function that was implemented on the deriving class if one exists.When simple commands are implemented using only the
handle()
function we may invoke that handle function directly using this call operator:class Command(TyperCommand): def handle(self, option1: bool, option2: bool): # invoked by this __call__ my_command = get_command('my_command') # invoke the handle() function directly my_command(option1=True, option2=False)
- classmethod callback(*, cls=<class 'django_typer.management.DTGroup'>, invoke_without_command=<typer.models.DefaultPlaceholder object>, no_args_is_help=<typer.models.DefaultPlaceholder object>, subcommand_metavar=<typer.models.DefaultPlaceholder object>, chain=<typer.models.DefaultPlaceholder object>, result_callback=<typer.models.DefaultPlaceholder object>, context_settings=<typer.models.DefaultPlaceholder object>, help=<typer.models.DefaultPlaceholder object>, epilog=<typer.models.DefaultPlaceholder object>, short_help=<typer.models.DefaultPlaceholder object>, options_metavar=<typer.models.DefaultPlaceholder object>, add_help_option=<typer.models.DefaultPlaceholder object>, hidden=<typer.models.DefaultPlaceholder object>, deprecated=<typer.models.DefaultPlaceholder object>, rich_help_panel=<typer.models.DefaultPlaceholder object>, **kwargs)¶
Override the initializer for this command class after it has been defined.
Note
See Tutorial: Inheritance & Plugins for details on when you might want to use this extension pattern.
from your_app.management.commands.your_command import Command as YourCommand @YourCommand.initialize() def init(self, ...): # implement your command initialization logic here
- Parameters:
name – the name of the callback (defaults to the name of the decorated function)
cls (Type[DTGroup]) – the command class to use - (the
initialize()
function is technically the root command group)invoke_without_command (bool) – whether to invoke the callback if no command was specified.
no_args_is_help (bool) – whether to show the help if no arguments are provided
subcommand_metavar (str | None) – the metavar to use for subcommands in the help output
chain (bool) – whether to chain commands, this allows multiple commands from the group to be specified and run in order sequentially in one call from the command line.
result_callback (Callable[[...], Any] | None) – a callback to invoke with the result of the command
context_settings (Dict[Any, Any] | None) – the click context settings to use - see
click.Context
.help (str | Promise | None) – the help string to use, defaults to the function docstring, if you need to translate the help you should use the help kwarg instead because docstrings will not be translated.
epilog (str | None) – the epilog to use in the help output
short_help (str | Promise | None) – the short help to use in the help output
options_metavar (str) – the metavar to use for options in the help output
add_help_option (bool) – whether to add the help option to the command
hidden (bool) – whether to hide this group from the help output
deprecated (bool) – show a deprecation warning
rich_help_panel (str | None) – the rich help panel to use - if rich is installed this can be used to group commands into panels in the help output.
kwargs (Any)
- Return type:
- classmethod command(name=None, *, cls=<class 'django_typer.management.DTCommand'>, context_settings=None, help=None, epilog=None, short_help=None, options_metavar='[OPTIONS]', add_help_option=True, no_args_is_help=False, hidden=False, deprecated=False, rich_help_panel=<typer.models.DefaultPlaceholder object>, **kwargs)[source]¶
Add a command to this command class after it has been defined. You can use this decorator to add commands to a root command from other Django apps.
Note
See Tutorial: Inheritance & Plugins for details on when you might want to use this extension pattern.
from your_app.management.commands.your_command import Command as YourCommand @YourCommand.command() def new_command(self, ...): # implement your additional command here
- Parameters:
name (str | None) – the name of the command (defaults to the name of the decorated function)
context_settings (Dict[Any, Any] | None) – the context settings to use - see
click.Context
help (str | Promise | None) – the help string to use, defaults to the function docstring, if you need the help to be translated you should use the help kwarg instead because docstrings will not be translated.
epilog (str | None) – the epilog to use in the help output
short_help (str | Promise | None) – the short help to use in the help output
options_metavar (str) – the metavar to use for options in the help output
add_help_option (bool) – whether to add the help option to the command
no_args_is_help (bool) – whether to show the help if no arguments are provided
hidden (bool) – whether to hide the command from help output
deprecated (bool) – show a deprecation warning
rich_help_panel (str | None) – the rich help panel to use - if rich is installed this can be used to group commands into panels in the help output.
kwargs (Any)
- Return type:
- property command_tree: CommandNode¶
Get the root CommandNode for this command. Allows easy traversal of the command tree.
- create_parser(prog_name, subcommand, **_)[source]¶
Create a parser for this command. This also sets the command context, so any functions below this call on the stack may use
django_typer.utils.get_current_command()
to retrieve the django command instance.
- echo(message=None, nl=True, err=False)[source]¶
A wrapper for typer.echo() that response
--no-color
and--force-color
flags, and writes to the command’s stdout.
- execute(*args, **options)[source]¶
Wrap the
execute()
method to set and unset no_color and force_color options.This function pushes the command onto the stack so any frame below this call may use get_current_command() to get a reference to the command instance.
args and options are passed to
handle()
.- Parameters:
args – the arguments to pass to the command
options – the options to pass to the command
- Returns:
Any object returned by the command
- classmethod finalize()[source]¶
Override the finalizer for this command class after it has been defined.
Note
See Tutorial: Inheritance & Plugins for details on when you might want to use this extension pattern.
from your_app.management.commands.your_command import Command as YourCommand @YourCommand.finalize() def collect(self, ...): # implement your command result collection logic here
- get_subcommand(*command_path)[source]¶
Retrieve a
CommandNode
at the given command path.- Parameters:
command_path (str) – the path to the command to retrieve, where each argument is the string name in order of a group or command in the hierarchy.
- Returns:
the command node at the given path
- Raises:
LookupError – if no group or command exists at the given path
- Return type:
- classmethod group(name=<typer.models.DefaultPlaceholder object>, cls=<class 'django_typer.management.DTGroup'>, invoke_without_command=<typer.models.DefaultPlaceholder object>, no_args_is_help=<typer.models.DefaultPlaceholder object>, subcommand_metavar=<typer.models.DefaultPlaceholder object>, chain=<typer.models.DefaultPlaceholder object>, result_callback=<typer.models.DefaultPlaceholder object>, context_settings=<typer.models.DefaultPlaceholder object>, help=<typer.models.DefaultPlaceholder object>, epilog=<typer.models.DefaultPlaceholder object>, short_help=<typer.models.DefaultPlaceholder object>, options_metavar=<typer.models.DefaultPlaceholder object>, add_help_option=<typer.models.DefaultPlaceholder object>, hidden=<typer.models.DefaultPlaceholder object>, deprecated=<typer.models.DefaultPlaceholder object>, rich_help_panel=<typer.models.DefaultPlaceholder object>, **kwargs)[source]¶
Add a group to this command class after it has been defined. You can use this decorator to add groups to a root command from other Django apps.
Note
See Tutorial: Inheritance & Plugins for details on when you might want to use this extension pattern.
from your_app.management.commands.your_command import Command as YourCommand @YourCommand.group() def new_group(self, ...): # implement your group initializer here @new_group.command() def grp_command(self, ...): # implement group subcommand here
- Parameters:
name (str | None) – the name of the group (defaults to the name of the decorated function)
invoke_without_command (bool) – whether to invoke the group callback if no command was specified.
no_args_is_help (bool) – whether to show the help if no arguments are provided
subcommand_metavar (str | None) – the metavar to use for subcommands in the help output
chain (bool) – whether to chain commands, this allows multiple commands from the group to be specified and run in order sequentially in one call from the command line.
result_callback (Callable[[...], Any] | None) – a callback to invoke with the result of the command
context_settings (Dict[Any, Any] | None) – the click context settings to use - see
click.Context
.help (str | Promise | None) – the help string to use, defaults to the function docstring, if you need to translate the help you should use the help kwarg instead because docstrings will not be translated.
epilog (str | None) – the epilog to use in the help output
short_help (str | Promise | None) – the short help to use in the help output
options_metavar (str) – the metavar to use for options in the help output
add_help_option (bool) – whether to add the help option to the command
hidden (bool) – whether to hide this group from the help output
deprecated (bool) – show a deprecation warning
rich_help_panel (str | None) – the rich help panel to use - if rich is installed this can be used to group commands into panels in the help output.
kwargs (Any)
- Return type:
Callable[[Callable[[Concatenate[TC, ~P]], R]], Typer[~P, R]]
- handle(*args, **options)¶
Invoke the underlying Typer app with the given arguments and parameters.
- Parameters:
args – the arguments to pass to the command, may be strings needing to be parsed, or already resolved object types the argument ultimately resolves to. TODO - check this is true
options – the options to pass to the command, may be strings needing to be parsed, or already resolved object types the option ultimately resolves to.
- Returns:
t.Any object returned by the Typer app
- classmethod initialize(*, cls=<class 'django_typer.management.DTGroup'>, invoke_without_command=<typer.models.DefaultPlaceholder object>, no_args_is_help=<typer.models.DefaultPlaceholder object>, subcommand_metavar=<typer.models.DefaultPlaceholder object>, chain=<typer.models.DefaultPlaceholder object>, result_callback=<typer.models.DefaultPlaceholder object>, context_settings=<typer.models.DefaultPlaceholder object>, help=<typer.models.DefaultPlaceholder object>, epilog=<typer.models.DefaultPlaceholder object>, short_help=<typer.models.DefaultPlaceholder object>, options_metavar=<typer.models.DefaultPlaceholder object>, add_help_option=<typer.models.DefaultPlaceholder object>, hidden=<typer.models.DefaultPlaceholder object>, deprecated=<typer.models.DefaultPlaceholder object>, rich_help_panel=<typer.models.DefaultPlaceholder object>, **kwargs)[source]¶
Override the initializer for this command class after it has been defined.
Note
See Tutorial: Inheritance & Plugins for details on when you might want to use this extension pattern.
from your_app.management.commands.your_command import Command as YourCommand @YourCommand.initialize() def init(self, ...): # implement your command initialization logic here
- Parameters:
name – the name of the callback (defaults to the name of the decorated function)
cls (Type[DTGroup]) – the command class to use - (the
initialize()
function is technically the root command group)invoke_without_command (bool) – whether to invoke the callback if no command was specified.
no_args_is_help (bool) – whether to show the help if no arguments are provided
subcommand_metavar (str | None) – the metavar to use for subcommands in the help output
chain (bool) – whether to chain commands, this allows multiple commands from the group to be specified and run in order sequentially in one call from the command line.
result_callback (Callable[[...], Any] | None) – a callback to invoke with the result of the command
context_settings (Dict[Any, Any] | None) – the click context settings to use - see
click.Context
.help (str | Promise | None) – the help string to use, defaults to the function docstring, if you need to translate the help you should use the help kwarg instead because docstrings will not be translated.
epilog (str | None) – the epilog to use in the help output
short_help (str | Promise | None) – the short help to use in the help output
options_metavar (str) – the metavar to use for options in the help output
add_help_option (bool) – whether to add the help option to the command
hidden (bool) – whether to hide this group from the help output
deprecated (bool) – show a deprecation warning
rich_help_panel (str | None) – the rich help panel to use - if rich is installed this can be used to group commands into panels in the help output.
kwargs (Any)
- Return type:
- print_help(prog_name, subcommand, *cmd_path)[source]¶
Print the help message for this command to stdout of the django command.
- Parameters:
prog_name (str) – the name of the manage script that invoked the command
subcommand (str) – the name of the django command
cmd_path (str) – the path to the command to print the help for. This is an extension to the base class
print_help()
interface, required because typer/click have different helps for each subgroup or subcommand.
- run_from_argv(argv)[source]¶
Wrap the
run_from_argv()
method to push the command onto the stack so any code in frames below this can get a reference to the command instance usingget_current_command()
.- Parameters:
argv – the arguments to pass to the command
- secho(message=None, nl=True, err=False, **styles)[source]¶
A wrapper for typer.secho() that response
--no-color
and--force-color
flags, and writes to the command’s stdout.
- class django_typer.management.BoundProxy(command, proxied)[source]¶
Bases:
Generic
[P
,R
]A helper class that proxies the Typer or command objects and binds them to the django command instance.
- Parameters:
command (TyperCommand)
proxied (Typer[~P, R] | CommandInfo | TyperInfo | Callable[[...], Any] | Finalizer)
- class django_typer.management.DTCommand(*args, callback, params=None, **kwargs)[source]¶
Bases:
DjangoTyperMixin
,TyperCommand
This class extends the
TyperCommand
class to work with the django-typer interfaces. If you need to add functionality to the command class - you should inherit from this class. You can then pass your custom class to thecommand()
decorators using the cls parameter.from django_typer import TyperCommand, DTCommand, command class CustomCommand(DTCommand): ... class Command(TyperCommand): @command(cls=CustomCommand) def handle(self): ...
See Commands and Groups for more information.
- class django_typer.management.DTGroup(*args, callback, params=None, **kwargs)[source]¶
Bases:
DjangoTyperMixin
,TyperGroup
This class extends the TyperGroup class to work with the django-typer interfaces. If you need to add functionality to the group class you should inherit from this class. You can then pass your custom class to the
command()
decorators using the cls parameter.from django_typer import TyperCommand, DTGroup, group class CustomGroup(DTGroup): ... class Command(TyperCommand): @group(cls=CustomGroup) def grp(self): ...
See click docs on custom groups and Advanced Patterns for more information.
- class django_typer.management.DjangoTyperMixin(*args, callback, params=None, **kwargs)[source]¶
Bases:
object
A mixin we use to add additional needed contextual awareness to click Commands and Groups.
- class Converter[source]¶
Bases:
object
Because of the way the BaseCommand forces parsing to be done in a separate first step, type casting of input strings to the correct types will have sometimes happened already. We use this class to avoid double type casting.
An alternative approach might be to flag converted values - but there does not seem to be a good approach to do this given how deep in the click infrastructure the conversion happens.
- common_params()[source]¶
Add the common parameters to this group only if this group is the root command’s user specified initialize callback.
- get_params(ctx)[source]¶
We override get_params to check to make sure that prompt_required is not set for parameters that have already been prompted for during the initial parse phase. We have to do this because of we’re stuffing the click infrastructure into the django infrastructure and the django infrastructure forces a two step parse process whereas click does not easily support separating these.
There may be a more sound approach than this?
- django_typer.management.callback(*, cls=<class 'django_typer.management.DTGroup'>, invoke_without_command=<typer.models.DefaultPlaceholder object>, no_args_is_help=<typer.models.DefaultPlaceholder object>, subcommand_metavar=<typer.models.DefaultPlaceholder object>, chain=<typer.models.DefaultPlaceholder object>, result_callback=<typer.models.DefaultPlaceholder object>, context_settings=<typer.models.DefaultPlaceholder object>, help=<typer.models.DefaultPlaceholder object>, epilog=<typer.models.DefaultPlaceholder object>, short_help=<typer.models.DefaultPlaceholder object>, options_metavar=<typer.models.DefaultPlaceholder object>, add_help_option=<typer.models.DefaultPlaceholder object>, hidden=<typer.models.DefaultPlaceholder object>, deprecated=<typer.models.DefaultPlaceholder object>, rich_help_panel=<typer.models.DefaultPlaceholder object>, **kwargs)¶
A function decorator that creates a Typer callback. This decorator wraps the Typer.callback() functionality. We’ve renamed it to
initialize()
becausecallback()
is to general and not intuitive. Callbacks in Typer are functions that are invoked before a command is invoked and that can accept their own arguments. When aninitialize()
function is supplied to a djangoTyperCommand
the default Django options will be added as parameters. You can specify these parameters (seedjango_typer.types
) as arguments on the wrapped function if you wish to receive them - otherwise they will be intercepted by the base class infrastructure and used to their purpose.The parameters are passed through to Typer.callback()
For example the below command defines two subcommands that both have a common initializer that accepts a –precision parameter option:
management/commands/math.py¶1import typing as t 2from typer import Argument, Option 3from django_typer import TyperCommand, initialize, command 4 5 6class Command(TyperCommand): 7 8 precision = 2 9 10 @initialize(help="Do some math at the given precision.") 11 def init( 12 self, 13 precision: t.Annotated[ 14 int, Option(help="The number of decimal places to output.") 15 ] = precision, 16 ): 17 self.precision = precision 18 19 @command(help="Multiply the given numbers.") 20 def multiply( 21 self, 22 numbers: t.Annotated[ 23 t.List[float], Argument(help="The numbers to multiply") 24 ], 25 ): 26 ... 27 28 @command() 29 def divide( 30 self, 31 numerator: t.Annotated[float, Argument(help="The numerator")], 32 denominator: t.Annotated[float, Argument(help="The denominator")] 33 ): 34 ...
When we run, the command we should provide the –precision option before the subcommand:
$ ./manage.py math --precision 5 multiply 2 2.333 4.66600
- Parameters:
name – the name of the callback (defaults to the name of the decorated function)
cls (Type[DTGroup]) – the command class to use - (the
initialize()
function is technically the root command group)invoke_without_command (bool) – whether to invoke the callback if no command was specified.
no_args_is_help (bool) – whether to show the help if no arguments are provided
subcommand_metavar (str | None) – the metavar to use for subcommands in the help output
chain (bool) – whether to chain commands, this allows multiple commands from the group to be specified and run in order sequentially in one call from the command line.
result_callback (Callable[[...], Any] | None) – a callback to invoke with the result of the command
context_settings (Dict[Any, Any] | None) – the click context settings to use - see
click.Context
.help (str | Promise | None) – the help string to use, defaults to the function docstring, if you need to translate the help you should use the help kwarg instead because docstrings will not be translated.
epilog (str | None) – the epilog to use in the help output
short_help (str | Promise | None) – the short help to use in the help output
options_metavar (str) – the metavar to use for options in the help output
add_help_option (bool) – whether to add the help option to the command
hidden (bool) – whether to hide this group from the help output
deprecated (bool) – show a deprecation warning
rich_help_panel (str | None) – the rich help panel to use - if rich is installed this can be used to group commands into panels in the help output.
kwargs (Any)
- Return type:
- django_typer.management.command(name=None, *, cls=<class 'django_typer.management.DTCommand'>, context_settings=None, help=None, epilog=None, short_help=None, options_metavar='[OPTIONS]', add_help_option=True, no_args_is_help=False, hidden=False, deprecated=False, rich_help_panel=<typer.models.DefaultPlaceholder object>, **kwargs)[source]¶
A function decorator that creates a new command and attaches it to the root command group. This is a passthrough to Typer.command() and the options are the same, except we swap the default command class for our wrapper.
We do not need to decorate
handle()
functions with this decorator, but if we want to pass options upstream to typer we can:class Command(TyperCommand): @command(epilog="This is the epilog for the command.") def handle(self): ...
We can also use the command decorator to define multiple subcommands:
class Command(TyperCommand): @command() def command1(self): # execute command1 logic here @command(name='command2') def other_command(self): # arguments passed to the decorator are passed to typer and control # various aspects of the command, for instance here we've changed the # name of the command to 'command2' from 'other_command'
The decorated function is the command function. It may also be invoked directly as a method from an instance of the
TyperCommand
class, seeget_command()
.- Parameters:
name (str | None) – the name of the command (defaults to the name of the decorated function)
context_settings (Dict[Any, Any] | None) – the context settings to use - see
click.Context
help (str | Promise | None) – the help string to use, defaults to the function docstring, if you need the help to be translated you should use the help kwarg instead because docstrings will not be translated.
epilog (str | None) – the epilog to use in the help output
short_help (str | Promise | None) – the short help to use in the help output
options_metavar (str) – the metavar to use for options in the help output
add_help_option (bool) – whether to add the help option to the command
no_args_is_help (bool) – whether to show the help if no arguments are provided
hidden (bool) – whether to hide the command from help output
deprecated (bool) – show a deprecation warning
rich_help_panel (str | None) – the rich help panel to use - if rich is installed this can be used to group commands into panels in the help output.
kwargs (Any)
- Return type:
- django_typer.management.finalize()[source]¶
Attach a callback function that collects and finalizes results returned from any invoked subcommands. This is a wrapper around typer’s result_callback that extends it to work as a method and for non-compound commands.
class Command(TyperCommand, chain=True): @finalize() def collect(self, results: t.List[str]): return ", ".join(results) @command() def cmd1(self): return "result1" @command() def cmd2(self): return "result2"
$ ./manage.py command cmd1 cmd2 result1, result2
The callback must at minimum accept a single argument that is either a list of results or a singular result if the command is not compound. The callback may optionally accept named arguments that correspond to parameters at the given command group scope. These parameters will also be available on the current context.
- django_typer.management.get_command(command_name: str, stdout: IO[str] | None = None, stderr: IO[str] | None = None, no_color: bool = False, force_color: bool = False, **kwargs: Any) BaseCommand [source]¶
- django_typer.management.get_command(command_name: str, cmd_type: Type[C], stdout: IO[str] | None = None, stderr: IO[str] | None = None, no_color: bool = False, force_color: bool = False, **kwargs: Any) C
- django_typer.management.get_command(command_name: str, path0: str, *path: str, stdout: IO[str] | None = None, stderr: IO[str] | None = None, no_color: bool = False, force_color: bool = False, **kwargs: Any) MethodType
Get a Django command by its name and instantiate it with the provided options. This will work for subclasses of
BaseCommand
as well as forTyperCommand
subclasses. If subcommands are listed for aTyperCommand
, the method that corresponds to the command name will be returned. This method may then be invoked directly. If no subcommands are listed the command instance will be returned.Using
get_command
to fetch a command instance and then invoking the instance as a callable is the preferred way to executeTyperCommand
commands from code. The arguments and options passed to the __call__ method of the command should be fully resolved to their expected parameter types before being passed to the command. Thecall_command()
interface also works, but arguments must be unparsed strings and options may be either strings or resolved parameter types. The following is more efficient thancall_command()
.basic = get_command('basic') result = basic( arg1, arg2, arg3=0.5, arg4=1 )
Subcommands may be retrieved by passing the subcommand names as additional arguments:
divide = get_command('hierarchy', 'math', 'divide') result = divide(10, 2)
When fetching an entire
TyperCommand
(i.e. no group or subcommand path), you may supply the type of the expected TyperCommand as the second argument. This will allow the type system to infer the correct return type:from myapp.management.commands import Command as Hierarchy hierarchy: Hierarchy = get_command('hierarchy', Hierarchy)
Note
If get_command fetches a
BaseCommand
that does not implement __call__ get_command will make the command callable by adding a __call__ method that calls thehandle()
method of theBaseCommand
. This allows you to call the command likeget_command("command")()
with confidence.- Parameters:
command_name – the name of the command to get
path – the path walking down the group/command tree
stdout – the stdout stream to use
stderr – the stderr stream to use
no_color – whether to disable color
force_color – whether to force color
kwargs – t.Any other parameters to pass through to the command constructor
- Raises:
ModuleNotFoundError – if the command is not found
LookupError – if the subcommand is not found
- django_typer.management.group(name=<typer.models.DefaultPlaceholder object>, cls=<class 'django_typer.management.DTGroup'>, invoke_without_command=<typer.models.DefaultPlaceholder object>, no_args_is_help=<typer.models.DefaultPlaceholder object>, subcommand_metavar=<typer.models.DefaultPlaceholder object>, chain=<typer.models.DefaultPlaceholder object>, result_callback=<typer.models.DefaultPlaceholder object>, context_settings=<typer.models.DefaultPlaceholder object>, help=<typer.models.DefaultPlaceholder object>, epilog=<typer.models.DefaultPlaceholder object>, short_help=<typer.models.DefaultPlaceholder object>, options_metavar=<typer.models.DefaultPlaceholder object>, add_help_option=<typer.models.DefaultPlaceholder object>, hidden=<typer.models.DefaultPlaceholder object>, deprecated=<typer.models.DefaultPlaceholder object>, rich_help_panel=<typer.models.DefaultPlaceholder object>, **kwargs)[source]¶
A function decorator that creates a new subgroup and attaches it to the root command group. This is like creating a new Typer app and adding it to a parent Typer app. The kwargs are passed through to the
Typer()
constructor. Thegroup()
functions work likeinitialize()
functions for their command groups.management/commands/example.py¶from django_typer import TyperCommand, group class Command(TyperCommand): @group() def group1(self, flag: bool = False): # do group init stuff here # to attach a command to the group, use the command() decorator # on the group function @group1.command() def command1(self): ... # you can also attach subgroups to groups! @group1.group() def subgroup(self): # do subgroup init stuff here @subgroup.command() def subcommand(self): ...
These groups and subcommands can be invoked from the command line like so:
$ ./manage.py example group1 --flag command1 $ ./manage.py example group1 --flag subgroup subcommand
- Parameters:
name (str | None) – the name of the group (defaults to the name of the decorated function)
invoke_without_command (bool) – whether to invoke the group callback if no command was specified.
no_args_is_help (bool) – whether to show the help if no arguments are provided
subcommand_metavar (str | None) – the metavar to use for subcommands in the help output
chain (bool) – whether to chain commands, this allows multiple commands from the group to be specified and run in order sequentially in one call from the command line.
result_callback (Callable[[...], Any] | None) – a callback to invoke with the result of the command
context_settings (Dict[Any, Any] | None) – the click context settings to use - see
click.Context
help (str | Promise | None) – the help string to use, defaults to the function docstring, if you need to translate the help you should use the help kwarg instead because docstrings will not be translated.
epilog (str | None) – the epilog to use in the help output
short_help (str | Promise | None) – the short help to use in the help output
options_metavar (str) – the metavar to use for options in the help output
add_help_option (bool) – whether to add the help option to the command
hidden (bool) – whether to hide this group from the help output
deprecated (bool) – show a deprecation warning
rich_help_panel (str | None) – the rich help panel to use - if rich is installed this can be used to group commands into panels in the help output.
kwargs (Any)
- Return type:
Callable[[Callable[[Concatenate[TC, ~P]], R]], Typer[~P, R]]
- django_typer.management.initialize(*, cls=<class 'django_typer.management.DTGroup'>, invoke_without_command=<typer.models.DefaultPlaceholder object>, no_args_is_help=<typer.models.DefaultPlaceholder object>, subcommand_metavar=<typer.models.DefaultPlaceholder object>, chain=<typer.models.DefaultPlaceholder object>, result_callback=<typer.models.DefaultPlaceholder object>, context_settings=<typer.models.DefaultPlaceholder object>, help=<typer.models.DefaultPlaceholder object>, epilog=<typer.models.DefaultPlaceholder object>, short_help=<typer.models.DefaultPlaceholder object>, options_metavar=<typer.models.DefaultPlaceholder object>, add_help_option=<typer.models.DefaultPlaceholder object>, hidden=<typer.models.DefaultPlaceholder object>, deprecated=<typer.models.DefaultPlaceholder object>, rich_help_panel=<typer.models.DefaultPlaceholder object>, **kwargs)[source]¶
A function decorator that creates a Typer callback. This decorator wraps the Typer.callback() functionality. We’ve renamed it to
initialize()
becausecallback()
is to general and not intuitive. Callbacks in Typer are functions that are invoked before a command is invoked and that can accept their own arguments. When aninitialize()
function is supplied to a djangoTyperCommand
the default Django options will be added as parameters. You can specify these parameters (seedjango_typer.types
) as arguments on the wrapped function if you wish to receive them - otherwise they will be intercepted by the base class infrastructure and used to their purpose.The parameters are passed through to Typer.callback()
For example the below command defines two subcommands that both have a common initializer that accepts a –precision parameter option:
management/commands/math.py¶1import typing as t 2from typer import Argument, Option 3from django_typer import TyperCommand, initialize, command 4 5 6class Command(TyperCommand): 7 8 precision = 2 9 10 @initialize(help="Do some math at the given precision.") 11 def init( 12 self, 13 precision: t.Annotated[ 14 int, Option(help="The number of decimal places to output.") 15 ] = precision, 16 ): 17 self.precision = precision 18 19 @command(help="Multiply the given numbers.") 20 def multiply( 21 self, 22 numbers: t.Annotated[ 23 t.List[float], Argument(help="The numbers to multiply") 24 ], 25 ): 26 ... 27 28 @command() 29 def divide( 30 self, 31 numerator: t.Annotated[float, Argument(help="The numerator")], 32 denominator: t.Annotated[float, Argument(help="The denominator")] 33 ): 34 ...
When we run, the command we should provide the –precision option before the subcommand:
$ ./manage.py math --precision 5 multiply 2 2.333 4.66600
- Parameters:
name – the name of the callback (defaults to the name of the decorated function)
cls (Type[DTGroup]) – the command class to use - (the
initialize()
function is technically the root command group)invoke_without_command (bool) – whether to invoke the callback if no command was specified.
no_args_is_help (bool) – whether to show the help if no arguments are provided
subcommand_metavar (str | None) – the metavar to use for subcommands in the help output
chain (bool) – whether to chain commands, this allows multiple commands from the group to be specified and run in order sequentially in one call from the command line.
result_callback (Callable[[...], Any] | None) – a callback to invoke with the result of the command
context_settings (Dict[Any, Any] | None) – the click context settings to use - see
click.Context
.help (str | Promise | None) – the help string to use, defaults to the function docstring, if you need to translate the help you should use the help kwarg instead because docstrings will not be translated.
epilog (str | None) – the epilog to use in the help output
short_help (str | Promise | None) – the short help to use in the help output
options_metavar (str) – the metavar to use for options in the help output
add_help_option (bool) – whether to add the help option to the command
hidden (bool) – whether to hide this group from the help output
deprecated (bool) – show a deprecation warning
rich_help_panel (str | None) – the rich help panel to use - if rich is installed this can be used to group commands into panels in the help output.
kwargs (Any)
- Return type:
- class django_typer.management.Context(command, parent=None, django_command=None, supplied_params=None, **kwargs)[source]¶
An extension of the
click.Context
class that adds a reference to theTyperCommand
instance so that the Django command can be accessed from within click and Typer callbacks that take a context. This context also keeps track of parameters that were supplied tocall_command()
.- Parameters:
- class ParamDict(*args, supplied)[source]¶
An extension of dict we use to block updates to parameters that were supplied when the command was invoked via
call_command()
. This complexity is introduced by the hybrid parsing and option passing inherent tocall_command()
.
- property supplied_params: Dict[str, Any]¶
Get the parameters that were supplied when the command was invoked via
call_command()
, only the root context has these.
- class django_typer.management.Typer(*args, **kwargs)[source]¶
Typer adds additional groups of commands by adding Typer apps to parent Typer apps. This class extends the
typer.Typer
class so that we can add the additional information necessary to attach this app to the root app and other groups specified on the django command.- Parameters:
name – the name of the class being created
bases – the base classes of the class being created
attrs – the attributes of the class being created
cls – The class to use as the core typer group wrapper
invoke_without_command – whether to invoke the group callback if no command was specified.
no_args_is_help – whether to show the help if no arguments are provided
subcommand_metavar – the metavar to use for subcommands in the help output
chain – whether to chain commands, this allows multiple commands from the group to be specified and run in order sequentially in one call from the command line.
result_callback – a callback to invoke with the result of the command
context_settings – the click context settings to use - see
click.Context
.help – the help string to use, defaults to the function docstring, if you need to translate the help you should use the help kwarg instead because docstrings will not be translated.
epilog – the epilog to use in the help output
short_help – the short help to use in the help output
options_metavar – the metavar to use for options in the help output
add_help_option – whether to add the help option to the command
hidden – whether to hide this group from the help output
deprecated – show a deprecation warning
rich_markup_mode – the rich markup mode to use - if rich is installed this can be used to enable rich markup or Markdown in the help output. Can be “markdown”, “rich” or None to disable markup rendering.
rich_help_panel – the rich help panel to use - if rich is installed this can be used to group commands into panels in the help output.
pretty_exceptions_enable – whether to enable pretty exceptions - if rich is installed this can be used to enable pretty exception rendering. This will default to on if the traceback configuration settings installs the rich traceback handler. This allows tracebacks to be configured by the user on a per deployment basis in the settings file. We therefore do not advise hardcoding this value.
pretty_exceptions_show_locals – whether to show local variables in pretty exceptions - if rich is installed. This will default to the ‘show_locals’ setting in the traceback configuration setting (on by default). This allows tracebacks to be configured by the user on a per deployment basis in the settings file. We therefore do not advise hardcoding this value.
pretty_exceptions_short – whether to show short tracebacks in pretty exceptions - if rich is installed. This will default to the ‘short’ setting in the traceback configuration setting (off by default). This allows tracebacks to be configured by the user on a per deployment basis in the settings file. We therefore do not advise hardcoding this value.
kwargs (Any)
- Return type:
- __init__(*args, name=<typer.models.DefaultPlaceholder object>, cls=<class 'django_typer.management.DTGroup'>, invoke_without_command=<typer.models.DefaultPlaceholder object>, no_args_is_help=<typer.models.DefaultPlaceholder object>, subcommand_metavar=<typer.models.DefaultPlaceholder object>, chain=<typer.models.DefaultPlaceholder object>, result_callback=<typer.models.DefaultPlaceholder object>, context_settings=<typer.models.DefaultPlaceholder object>, callback=<typer.models.DefaultPlaceholder object>, help=<typer.models.DefaultPlaceholder object>, epilog=<typer.models.DefaultPlaceholder object>, short_help=<typer.models.DefaultPlaceholder object>, options_metavar=<typer.models.DefaultPlaceholder object>, add_help_option=<typer.models.DefaultPlaceholder object>, hidden=<typer.models.DefaultPlaceholder object>, deprecated=<typer.models.DefaultPlaceholder object>, add_completion=True, rich_markup_mode=<typer.models.DefaultPlaceholder object>, rich_help_panel=<typer.models.DefaultPlaceholder object>, pretty_exceptions_enable=True, pretty_exceptions_show_locals=False, pretty_exceptions_short=True, parent=None, django_command=None, **kwargs)[source]¶
- Parameters:
name (str | None)
invoke_without_command (bool)
no_args_is_help (bool)
subcommand_metavar (str | None)
chain (bool)
callback (Callable[[Concatenate[TC, ~P]], R] | None)
help (str | Promise | None)
epilog (str | None)
short_help (str | Promise | None)
options_metavar (str)
add_help_option (bool)
hidden (bool)
deprecated (bool)
add_completion (bool)
rich_markup_mode (Literal['markdown', 'rich', None])
rich_help_panel (str | None)
pretty_exceptions_enable (bool)
pretty_exceptions_show_locals (bool)
pretty_exceptions_short (bool)
parent (Typer | None)
django_command (Type[TyperCommand] | None)
kwargs (Any)
- command(name=None, *, cls=<class 'django_typer.management.DTCommand'>, context_settings=None, help=None, epilog=None, short_help=None, options_metavar='[OPTIONS]', add_help_option=True, no_args_is_help=False, hidden=False, deprecated=False, rich_help_panel=<typer.models.DefaultPlaceholder object>, **kwargs)[source]¶
A function decorator that creates a new command and attaches it to this group. This is a passthrough to
Typer.command()
and the options are the same, except we swap the default command class for our wrapper.The decorated function is the command function. It may also be invoked directly as a method from an instance of the django command class.
class Command(TyperCommand): @group() def group1(self): pass @group1.command() def command1(self): # do stuff here
Note
If you need to use a different command class you will need to either inherit from django-typer or make sure yours is interface compatible with our extensions. You shouldn’t need to do this though - if the library does not do something you need it to please submit an issue.
- Parameters:
name (str | None) – the name of the command (defaults to the name of the decorated function)
context_settings (Dict[Any, Any] | None) – the context settings to use - see
click.Context
help (str | Promise | None) – the help string to use, defaults to the function docstring, if you need the help to be translated you should use the help kwarg instead because docstrings will not be translated.
epilog (str | None) – the epilog to use in the help output
short_help (str | Promise | None) – the short help to use in the help output
options_metavar (str) – the metavar to use for options in the help output
add_help_option (bool) – whether to add the help option to the command
no_args_is_help (bool) – whether to show the help if no arguments are provided
hidden (bool) – whether to hide the command from help output
deprecated (bool) – show a deprecation warning
rich_help_panel (str | None) – the rich help panel to use - if rich is installed this can be used to group commands into panels in the help output.
kwargs (Any)
- Return type:
- finalize()[source]¶
Add a finalizer callback to collect the results of all commands run as part of this command group. This is analogous to the
result_callback
onTyper.add_typer
but works seamlessly for methods. See Collect Results with @finalize for more information.
- group(name=<typer.models.DefaultPlaceholder object>, cls=<class 'django_typer.management.DTGroup'>, invoke_without_command=<typer.models.DefaultPlaceholder object>, no_args_is_help=<typer.models.DefaultPlaceholder object>, subcommand_metavar=<typer.models.DefaultPlaceholder object>, chain=<typer.models.DefaultPlaceholder object>, result_callback=<typer.models.DefaultPlaceholder object>, context_settings=<typer.models.DefaultPlaceholder object>, help=<typer.models.DefaultPlaceholder object>, epilog=<typer.models.DefaultPlaceholder object>, short_help=<typer.models.DefaultPlaceholder object>, options_metavar=<typer.models.DefaultPlaceholder object>, add_help_option=<typer.models.DefaultPlaceholder object>, hidden=<typer.models.DefaultPlaceholder object>, deprecated=<typer.models.DefaultPlaceholder object>, rich_help_panel=<typer.models.DefaultPlaceholder object>, **kwargs)[source]¶
Create a new subgroup and attach it to this group. This is like creating a new Typer app and adding it to a parent Typer app. The kwargs are passed through to the
Typer()
constructor.class Command(TyperCommand): @group() def group1(self): pass @group1.group() def subgroup(self): # do common group init stuff here @subgroup.command(help=_('My command does good stuff!')) def subcommand(self): # do command stuff here
- Parameters:
name (str | None) – the name of the group
invoke_without_command (bool) – whether to invoke the group callback if no command was specified.
no_args_is_help (bool) – whether to show the help if no arguments are provided
subcommand_metavar (str | None) – the metavar to use for subcommands in the help output
chain (bool) – whether to chain commands, this allows multiple commands from the group to be specified and run in order sequentially in one call from the command line.
result_callback (Callable[[...], Any] | None) – a callback to invoke with the result of the command
context_settings (Dict[Any, Any] | None) – the click context settings to use - see
click.Context
.help (str | Promise | None) – the help string to use, defaults to the function docstring, if you need to translate the help you should use the help kwarg instead because docstrings will not be translated.
epilog (str | None) – the epilog to use in the help output
short_help (str | Promise | None) – the short help to use in the help output
options_metavar (str) – the metavar to use for options in the help output
add_help_option (bool) – whether to add the help option to the command
hidden (bool) – whether to hide this group from the help output
deprecated (bool) – show a deprecation warning
rich_help_panel (str | None) – the rich help panel to use - if rich is installed this can be used to group commands into panels in the help output.
kwargs (Any)
- Return type:
Callable[[Callable[[Concatenate[TC, ~P2]], R2]], Typer[P2, R2]]
- class django_typer.management.TyperParser(django_command, prog_name, subcommand)[source]¶
A class that conforms to the argparse.ArgumentParser interface that the django base class works with that is returned by
create_parser()
. This class does not strictly conform to the argparse interface but does just enough to satisfy the django base class.- Parameters:
django_command (TyperCommand) – the django command instance
prog_name (str) – the name of the manage script that invoked the command
subcommand (str) – the name of the django command
- class Action(param)[source]¶
Emulate the interface of argparse.Action. Partial implementation used to satisfy the django BaseCommand class.
- Parameters:
param (Parameter) – the click parameter to wrap as an argparse Action
- property option_strings: List[str]¶
call_command uses this to determine a mapping of supplied options to function arguments. I.e. it will remap option_string: dest. We don’t want this because we’d rather have supplied parameters line up with their function arguments to allow deconfliction when CLI options share the same name.
- __init__(django_command, prog_name, subcommand)[source]¶
- Parameters:
django_command (TyperCommand)
- add_argument(*args, **kwargs)[source]¶
add_argument() is disabled for TyperCommands because all arguments and parameters are specified as args and kwargs on the function calls.
- parse_args(args=None, namespace=None)[source]¶
Parse the given arguments into a parsed arguments namespace object. If any arguments trigger termination of the command (like –help) then this method will exit the program.
Parse will also add the common django parameter defaults to the parsed arguments object.
- Parameters:
args – the arguments to parse
namespace – the namespace to populate with the parsed arguments (this is ignored for TyperCommands but is required by the django base class)
- Return type:
_ParsedArgs
- class django_typer.management.CommandNode(name, click_command, django_command, parent=None)[source]¶
A tree node that represents a command in the command tree. This is used to walk the click command hierarchy and produce helps and map command paths to command functions. The command tree is built on TyperCommand initialization.
- Parameters:
name (str) – the name of the command or subcommand
click_command (DjangoTyperMixin) – the click command object
context – the click context object
django_command (TyperCommand) – the django command instance
parent (Context | None) – the parent node or None if this is a root node
- __init__(name, click_command, django_command, parent=None)[source]¶
- Parameters:
name (str)
click_command (DjangoTyperMixin)
django_command (TyperCommand)
parent (Context | None)
- property children: Dict[str, CommandNode]¶
The child group and command nodes of this command node.
- click_command: DjangoTyperMixin¶
The click command object that this node represents.
- django_command: TyperCommand¶
Back reference to the django command instance that this command belongs to.
- get_command(*command_path)[source]¶
Return the command node for the given command path at or below this node.
- Parameters:
command_path (str) – the parent group names followed by the name of the command or group to retrieve
- Returns:
the command node at the given group/subcommand path
- Raises:
LookupError – if the command path does not exist
- Return type:
- class django_typer.management.TyperCommandMeta(cls_name, bases, attrs, name=<typer.models.DefaultPlaceholder object>, cls=<class 'django_typer.management.DTGroup'>, invoke_without_command=<typer.models.DefaultPlaceholder object>, no_args_is_help=<typer.models.DefaultPlaceholder object>, subcommand_metavar=<typer.models.DefaultPlaceholder object>, chain=<typer.models.DefaultPlaceholder object>, result_callback=<typer.models.DefaultPlaceholder object>, context_settings=<typer.models.DefaultPlaceholder object>, callback=<typer.models.DefaultPlaceholder object>, help=<typer.models.DefaultPlaceholder object>, epilog=<typer.models.DefaultPlaceholder object>, short_help=<typer.models.DefaultPlaceholder object>, options_metavar=<typer.models.DefaultPlaceholder object>, add_help_option=<typer.models.DefaultPlaceholder object>, hidden=<typer.models.DefaultPlaceholder object>, deprecated=<typer.models.DefaultPlaceholder object>, rich_markup_mode=<typer.models.DefaultPlaceholder object>, rich_help_panel=<typer.models.DefaultPlaceholder object>, pretty_exceptions_enable=<typer.models.DefaultPlaceholder object>, pretty_exceptions_show_locals=<typer.models.DefaultPlaceholder object>, pretty_exceptions_short=<typer.models.DefaultPlaceholder object>, **kwargs)[source]¶
The metaclass used to build the TyperCommand class. This metaclass is responsible for building Typer app using the arguments supplied to the TyperCommand constructor. It also discovers if
handle()
was supplied as the single command implementation.Warning
This metaclass is private because it may change substantially in the future to support changes in the upstream libraries. The TyperCommand interface should be considered the stable interface.
- Parameters:
name (str | None) – the name of the class being created
bases – the base classes of the class being created
attrs – the attributes of the class being created
cls (Type[DTGroup] | None) – The class to use as the core typer group wrapper
invoke_without_command (bool) – whether to invoke the group callback if no command was specified.
no_args_is_help (bool) – whether to show the help if no arguments are provided
subcommand_metavar (str | None) – the metavar to use for subcommands in the help output
chain (bool) – whether to chain commands, this allows multiple commands from the group to be specified and run in order sequentially in one call from the command line.
result_callback (Callable[[...], Any] | None) – a callback to invoke with the result of the command
context_settings (Dict[Any, Any] | None) – the click context settings to use - see
click.Context
help (str | Promise | None) – the help string to use, defaults to the function docstring, if you need to translate the help you should use the help kwarg instead because docstrings will not be translated.
epilog (str | None) – the epilog to use in the help output
short_help (str | Promise | None) – the short help to use in the help output
options_metavar (str) – the metavar to use for options in the help output
add_help_option (bool) – whether to add the help option to the command
hidden (bool) – whether to hide this group from the help output
deprecated (bool) – show a deprecation warning
rich_markup_mode (Literal['markdown', 'rich', None]) – the rich markup mode to use - if rich is installed this can be used to enable rich markup or Markdown in the help output. Can be “markdown”, “rich” or None to disable markup rendering.
rich_help_panel (str | None) – the rich help panel to use - if rich is installed this can be used to group commands into panels in the help output.
pretty_exceptions_enable (DefaultPlaceholder | bool) – whether to enable pretty exceptions - if rich is installed this can be used to enable pretty exception rendering. This will default to on if the traceback configuration settings installs the rich traceback handler. This allows tracebacks to be configured by the user on a per deployment basis in the settings file. We therefore do not advise hardcoding this value.
pretty_exceptions_show_locals (DefaultPlaceholder | bool) – whether to show local variables in pretty exceptions - if rich is installed. This will default to the ‘show_locals’ setting in the traceback configuration setting (on by default). This allows tracebacks to be configured by the user on a per deployment basis in the settings file. We therefore do not advise hardcoding this value.
pretty_exceptions_short (DefaultPlaceholder | bool) – whether to show short tracebacks in pretty exceptions - if rich is installed. This will default to the ‘short’ setting in the traceback configuration setting (off by default). This allows tracebacks to be configured by the user on a per deployment basis in the settings file. We therefore do not advise hardcoding this value.
kwargs (Any)