Utils

A collection of useful utilities.

django_typer.utils.duration_iso_string(duration)[source]

Return an ISO8601 duration string from a timedelta. This differs from the Django implementation in that zeros are elided.

Parameters:

duration (timedelta)

Return type:

str

django_typer.utils.get_current_command()[source]

Returns the current typer command. This can be used as a way to access the current command object from anywhere if we are executing inside of one from higher on the stack. We primarily need this because certain monkey patches are required in typer code - namely for enabling/disabling color based on configured parameters.

This function is thread safe.

This is analogous to click’s get_current_context but for command execution.

Returns:

The current typer command or None if there is no active command.

Return type:

TyperCommand | None

django_typer.utils.is_method(func_or_params)[source]

This logic is used to to determine if a function should be bound as a method or not. Right now django-typer will treat module scope functions as methods when binding to command classes if they have a first argument named ‘self’.

Parameters:
  • func – The function to check or a list of parameter names, or None

  • func_or_params (Callable[[...], Any] | List[str] | None)

Returns:

True if the function should be considered a method, False if not and None if undetermined.

Return type:

bool | None

django_typer.utils.model_parser_completer(model_or_qry, lookup_field=None, case_insensitive=False, help_field=None, query=None, limit=50, distinct=True, on_error=None, order_by=None, return_type=ReturnType.MODEL_INSTANCE)[source]

A factory function that returns a dictionary that can be used to specify a parser and completer for a typer.Option or typer.Argument. This is a convenience function that can be used to specify the parser and completer for a model object in one go.

def handle(
    self,
    obj: t.Annotated[
        ModelClass,
        typer.Argument(
            **model_parser_completer(ModelClass, 'field_name'),
            help=_("Fetch objects by their field_names.")
        ),
    ]
):
    ...
Parameters:
  • model_or_qry (Type[Model] | QuerySet) – the model class or QuerySet to use for lookup

  • lookup_field (str | None) – the field to use for lookup, by default the primary key

  • case_insensitive (bool) – whether to perform case insensitive lookups and completions, default: False

  • help_field (str | None) – the field to use for help output in completion suggestions, by default no help will be provided

  • query (Callable[[ModelObjectCompleter, Context, Parameter, str], Q] | None) – a callable that will be used to build the query for completions, by default the query will be reasonably determined by the field type

  • limit (int | None) – the maximum number of completions to return, default: 50

  • distinct (bool) – whether to filter out already provided parameters in the completion suggestions, True by default

  • on_error (Callable[[Type[Model], str, Exception], None] | None) – a callable that will be called if the parser lookup fails to produce a matching object - by default a CommandError will be raised

  • return_type (ReturnType) – An enumeration switch to return either a model instance, queryset or model field value type.

  • order_by (Sequence[str] | str | None)

Return type:

Dict[str, Any]

django_typer.utils.parse_iso_duration(duration)[source]

Progressively parse an ISO8601 duration type - can be a partial duration string. If it is a partial duration string with an ambiguous trailing number, the number will be returned as the second value of the tuple.

Note

We use a subset of ISO8601, the supported markers are D, H, M, S.

Returns:

A tuple of the parsed duration and the ambiguous trailing number

Parameters:

duration (str)

Return type:

Tuple[timedelta, str | None]

django_typer.utils.register_command_plugins(package, commands=None)[source]

Register a command plugin for the given command within the given package.

For example, use this in your AppConfig’s ready() method:

from django.apps import AppConfig
from django_typer.utils import register_command_plugins


class MyAppConfig(AppConfig):
    name = "myapp"

    def ready(self):
        from .management import plugins

        register_command_plugins(plugins)
Parameters:
  • package (ModuleType) – The package the command extension module resides in

  • commands (List[str] | None) – The names of the commands/modules, if not provided, all modules in the package will be registered as plugins

django_typer.utils.traceback_config()[source]

Fetch the rich traceback installation parameters from our settings. By default rich tracebacks are on with show_locals = True. If the config is set to False or None rich tracebacks will not be installed even if the library is present.

This allows us to have a common traceback configuration for all commands. If rich tracebacks are managed separately this setting can also be switched off.

Return type:

Dict[str, Any]