Skip to main content

Use Typer to define the CLI for your Django management commands.

Project description

MIT license PyPI version fury.io PyPI pyversions PyPI djversions PyPI status Documentation Status Code Cov Test Status Lint Status Code Style

django-typer

Use Typer to define the CLI for your Django management commands. Provides a TyperCommand class that inherits from BaseCommand and allows typer-style annotated parameter types. All of the BaseCommand functionality is preserved, so that TyperCommand can be a drop in replacement.

django-typer makes it easy to:

  • Define your command CLI interface in a clear, DRY and safe way using type hints

  • Create subcommand and group command hierarchies.

  • Use the full power of Typer’s parameter types to validate and parse command line inputs.

  • Create beautiful and information dense help outputs.

  • Configure the rendering of exception stack traces using rich.

  • Install shell tab-completion support for TyperCommands and normal Django commands for bash, zsh, fish and powershell.

  • Create custom and portable shell tab-completions for your CLI parameters.

  • Refactor existing management commands into TyperCommands because TyperCommand is interface compatible with BaseCommand.

Please refer to the full documentation for more information.

https://github.com/bckohan/django-typer/blob/181b7c7d26cdd2f009b89ddc509c84c279473461/doc/source/_static/img/closepoll_example.gif

Installation

  1. Clone django-typer from GitHub or install a release off PyPI:

    pip install django-typer

    rich is a powerful library for rich text and beautiful formatting in the terminal. It is not required, but highly recommended for the best experience:

    pip install "django-typer[rich]"
  2. Add django_typer to your INSTALLED_APPS setting:

    INSTALLED_APPS = [
        ...
        'django_typer',
    ]

Basic Example

For example TyperCommands can be a very simple drop in replacement for BaseCommands. All of the documented features of BaseCommand work!

from django_typer import TyperCommand


class Command(TyperCommand):

   def handle(self, arg1: str, arg2: str, arg3: float = 0.5, arg4: int = 1):
      """
      A basic command that uses Typer
      """
https://raw.githubusercontent.com/bckohan/django-typer/main/django_typer/examples/helps/basic.svg

Multiple Subcommands Example

Or commands with multiple subcommands can be defined:

import typing as t

from django.utils.translation import gettext_lazy as _
from typer import Argument

from django_typer import TyperCommand, command


class Command(TyperCommand):
   """
   A command that defines subcommands.
   """

   @command()
   def create(
      self,
      name: t.Annotated[str, Argument(help=_("The name of the object to create."))],
   ):
      """
      Create an object.
      """
      ...

   @command()
   def delete(
      self, id: t.Annotated[int, Argument(help=_("The id of the object to delete."))]
   ):
      """
      Delete an object.
      """
      ...
https://raw.githubusercontent.com/bckohan/django-typer/main/django_typer/examples/helps/multi.svg https://raw.githubusercontent.com/bckohan/django-typer/main/django_typer/examples/helps/multi_create.svg https://raw.githubusercontent.com/bckohan/django-typer/main/django_typer/examples/helps/multi_delete.svg

Grouping and Hierarchies Example

Or more complex groups and subcommand hierarchies can be defined. For example this command defines a group of commands called math, with subcommands divide and multiply. The group has a common initializer that optionally sets a float precision value. We would invoke this command like so:

./manage.py hierarchy math --precision 5 divide 10 2.1
4.76190
./manage.py hierarchy math multiply 10 2
20.00

Any number of groups and subcommands and subgroups of other groups can be defined allowing for arbitrarily complex command hierarchies.

import typing as t
from functools import reduce

from django.utils.translation import gettext_lazy as _
from typer import Argument, Option

from django_typer import TyperCommand, group


class Command(TyperCommand):

   help = _("A more complex command that defines a hierarchy of subcommands.")

   precision = 2

   @group(help=_("Do some math at the given precision."))
   def math(
      self,
      precision: t.Annotated[
         int, Option(help=_("The number of decimal places to output."))
      ] = precision,
   ):
      self.precision = precision

   @math.command(help=_("Multiply the given numbers."))
   def multiply(
      self,
      numbers: t.Annotated[
         t.List[float], Argument(help=_("The numbers to multiply"))
      ],
   ):
      if numbers:
         return f"{reduce(lambda x, y: x * y, [1, *numbers]):.{self.precision}f}"

   @math.command()
   def divide(
      self,
      numerator: t.Annotated[float, Argument(help=_("The numerator"))],
      denominator: t.Annotated[float, Argument(help=_("The denominator"))],
      floor: t.Annotated[bool, Option(help=_("Use floor division"))] = False,
   ):
      """
      Divide the given numbers.
      """
      if floor:
            return str(numerator // denominator)
      return f"{numerator / denominator:.{self.precision}f}"
https://raw.githubusercontent.com/bckohan/django-typer/main/django_typer/examples/helps/hierarchy.svg https://raw.githubusercontent.com/bckohan/django-typer/main/django_typer/examples/helps/hierarchy_math.svg https://raw.githubusercontent.com/bckohan/django-typer/main/django_typer/examples/helps/hierarchy_math_multiply.svg https://raw.githubusercontent.com/bckohan/django-typer/main/django_typer/examples/helps/hierarchy_math_divide.svg

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_typer-1.0.0.tar.gz (43.0 kB view details)

Uploaded Source

Built Distribution

django_typer-1.0.0-py3-none-any.whl (43.4 kB view details)

Uploaded Python 3

File details

Details for the file django_typer-1.0.0.tar.gz.

File metadata

  • Download URL: django_typer-1.0.0.tar.gz
  • Upload date:
  • Size: 43.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.0 CPython/3.11.4 Darwin/23.2.0

File hashes

Hashes for django_typer-1.0.0.tar.gz
Algorithm Hash digest
SHA256 33e6e837b9cb67ca2d680441ba9f8e3a057f603f54bb4f75d1e18718836854e9
MD5 0761e789a968fd14d264a1e1597d16f8
BLAKE2b-256 1d27a8e3eb618210c1828e7358095db50150b65ffab9b7843bb0be2037b3c79b

See more details on using hashes here.

File details

Details for the file django_typer-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: django_typer-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 43.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.0 CPython/3.11.4 Darwin/23.2.0

File hashes

Hashes for django_typer-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 ee0a967b23ef381e92edbf3b79bc0e74ee0cdf75932f68c236a1e4600857d55c
MD5 fd6bc65d2364b5256f5f0ee7f9c9d873
BLAKE2b-256 8d68fb63b1320d4bf2cb977005ee69c0496d279c3acfb14cfd8c67f090bf904c

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page