django-typer


Namedjango-typer JSON
Version 1.1.1 PyPI version JSON
download
home_pagehttps://django-typer.readthedocs.io
SummaryUse Typer to define the CLI for your Django management commands.
upload_time2024-04-11 18:50:14
maintainerNone
docs_urlNone
authorBrian Kohan
requires_python<4.0,>=3.8
licenseMIT
keywords django cli management typer commands
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # django-typer


[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
[![PyPI version](https://badge.fury.io/py/django-typer.svg)](https://pypi.python.org/pypi/django-typer/)
[![PyPI pyversions](https://img.shields.io/pypi/pyversions/django-typer.svg)](https://pypi.python.org/pypi/django-typer/)
[![PyPI djversions](https://img.shields.io/pypi/djversions/django-typer.svg)](https://pypi.org/project/django-typer/)
[![PyPI status](https://img.shields.io/pypi/status/django-typer.svg)](https://pypi.python.org/pypi/django-typer)
[![Documentation Status](https://readthedocs.org/projects/django-typer/badge/?version=latest)](http://django-typer.readthedocs.io/?badge=latest/)
[![Code Cov](https://codecov.io/gh/bckohan/django-typer/branch/main/graph/badge.svg?token=0IZOKN2DYL)](https://codecov.io/gh/bckohan/django-typer)
[![Test Status](https://github.com/bckohan/django-typer/workflows/test/badge.svg)](https://github.com/bckohan/django-typer/actions/workflows/test.yml)
[![Lint Status](https://github.com/bckohan/django-typer/workflows/lint/badge.svg)](https://github.com/bckohan/django-typer/actions/workflows/lint.yml)
[![Code Style](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)

Use [Typer](https://typer.tiangolo.com/) to define the CLI for your [Django](https://www.djangoproject.com/) management commands. Provides a TyperCommand class that inherits from [BaseCommand](https://docs.djangoproject.com/en/stable/howto/custom-management-commands/#django.core.management.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](https://django-typer.readthedocs.io/en/latest/shell_completion.html) for TyperCommands and normal Django commands for [bash](https://www.gnu.org/software/bash/), [zsh](https://www.zsh.org/), [fish](https://fishshell.com/), and [powershell](https://learn.microsoft.com/en-us/powershell/scripting/overview).
- [Create custom and portable shell tab-completions for your CLI parameters.](https://django-typer.readthedocs.io/en/latest/shell_completion.html#defining-custom-completions)
- Refactor existing management commands into TyperCommands because TyperCommand is interface compatible with BaseCommand.

Please refer to the [full documentation](https://django-typer.readthedocs.io/) for more information.

![django-typer example](https://raw.githubusercontent.com/bckohan/django-typer/main/doc/source/_static/img/closepoll_example.gif)

## Installation

1. Clone django-typer from GitHub or install a release off [PyPI](https://pypi.org/project/django-typer/):

   ```bash
   pip install django-typer
   ```

   [rich](https://rich.readthedocs.io/en/latest/) is a powerful library for rich text and beautiful formatting in the terminal. It is not required but highly recommended for the best experience:

   ```bash
   pip install "django-typer[rich]"
   ```

2. Add `django_typer` to your `INSTALLED_APPS` setting:

   ```python
   INSTALLED_APPS = [
       ...
       'django_typer',
   ]
   ```

*You only need to install django_typer as an app if you want to use the shell completion command to enable tab-completion or if you would like django-typer to install [rich traceback rendering](https://django-typer.readthedocs.io/en/latest/howto.html#configure-rich-stack-traces) for you - which it does by default if rich is also installed.*

## Basic Example

For example, TyperCommands can be a very simple drop-in replacement for BaseCommands. All of the documented features of [BaseCommand](https://docs.djangoproject.com/en/stable/howto/custom-management-commands/#django.core.management.BaseCommand) work!

```python
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
        """
```

![Basic Example](https://raw.githubusercontent.com/bckohan/django-typer/main/django_typer/examples/helps/basic.svg)

## Multiple Subcommands Example



Commands with multiple subcommands can be defined:

```python
   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.
         """

```

![Multiple Subcommands Example](https://raw.githubusercontent.com/bckohan/django-typer/main/django_typer/examples/helps/multi.svg)
![Multiple Subcommands Example - create](https://raw.githubusercontent.com/bckohan/django-typer/main/django_typer/examples/helps/multi_create.svg)
![Multiple Subcommands Example - delete](https://raw.githubusercontent.com/bckohan/django-typer/main/django_typer/examples/helps/multi_delete.svg)

## Grouping and Hierarchies Example

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:

```bash
./manage.py hierarchy math --precision 5 divide 10 2.1
./manage.py hierarchy math multiply 10 2
```

```python
   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"))
         ],
      ):
         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}"

```

![Grouping and Hierarchies Example](https://raw.githubusercontent.com/bckohan/django-typer/main/django_typer/examples/helps/hierarchy.svg)
![Grouping and Hierarchies Example - math](https://raw.githubusercontent.com/bckohan/django-typer/main/django_typer/examples/helps/hierarchy_math.svg)
![Grouping and Hierarchies Example - math multiply](https://raw.githubusercontent.com/bckohan/django-typer/main/django_typer/examples/helps/hierarchy_math_multiply.svg)
![Grouping and Hierarchies Example - math divide](https://raw.githubusercontent.com/bckohan/django-typer/main/django_typer/examples/helps/hierarchy_math_divide.svg)

            

Raw data

            {
    "_id": null,
    "home_page": "https://django-typer.readthedocs.io",
    "name": "django-typer",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<4.0,>=3.8",
    "maintainer_email": null,
    "keywords": "django, CLI, management, Typer, commands",
    "author": "Brian Kohan",
    "author_email": "bckohan@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/56/5f/2f7920e57f655461b491e85416a6054901469660c8d03d0c6aa4af1d0adc/django_typer-1.1.1.tar.gz",
    "platform": null,
    "description": "# django-typer\n\n\n[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)\n[![PyPI version](https://badge.fury.io/py/django-typer.svg)](https://pypi.python.org/pypi/django-typer/)\n[![PyPI pyversions](https://img.shields.io/pypi/pyversions/django-typer.svg)](https://pypi.python.org/pypi/django-typer/)\n[![PyPI djversions](https://img.shields.io/pypi/djversions/django-typer.svg)](https://pypi.org/project/django-typer/)\n[![PyPI status](https://img.shields.io/pypi/status/django-typer.svg)](https://pypi.python.org/pypi/django-typer)\n[![Documentation Status](https://readthedocs.org/projects/django-typer/badge/?version=latest)](http://django-typer.readthedocs.io/?badge=latest/)\n[![Code Cov](https://codecov.io/gh/bckohan/django-typer/branch/main/graph/badge.svg?token=0IZOKN2DYL)](https://codecov.io/gh/bckohan/django-typer)\n[![Test Status](https://github.com/bckohan/django-typer/workflows/test/badge.svg)](https://github.com/bckohan/django-typer/actions/workflows/test.yml)\n[![Lint Status](https://github.com/bckohan/django-typer/workflows/lint/badge.svg)](https://github.com/bckohan/django-typer/actions/workflows/lint.yml)\n[![Code Style](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)\n\nUse [Typer](https://typer.tiangolo.com/) to define the CLI for your [Django](https://www.djangoproject.com/) management commands. Provides a TyperCommand class that inherits from [BaseCommand](https://docs.djangoproject.com/en/stable/howto/custom-management-commands/#django.core.management.BaseCommand) and allows typer-style annotated parameter types. All of the BaseCommand functionality is preserved, so that TyperCommand can be a drop-in replacement.\n\n**django-typer makes it easy to:**\n\n- Define your command CLI interface in a clear, DRY, and safe way using type hints.\n- Create subcommand and group command hierarchies.\n- Use the full power of Typer's parameter types to validate and parse command line inputs.\n- Create beautiful and information dense help outputs.\n- Configure the rendering of exception stack traces using rich.\n- [Install shell tab-completion support](https://django-typer.readthedocs.io/en/latest/shell_completion.html) for TyperCommands and normal Django commands for [bash](https://www.gnu.org/software/bash/), [zsh](https://www.zsh.org/), [fish](https://fishshell.com/), and [powershell](https://learn.microsoft.com/en-us/powershell/scripting/overview).\n- [Create custom and portable shell tab-completions for your CLI parameters.](https://django-typer.readthedocs.io/en/latest/shell_completion.html#defining-custom-completions)\n- Refactor existing management commands into TyperCommands because TyperCommand is interface compatible with BaseCommand.\n\nPlease refer to the [full documentation](https://django-typer.readthedocs.io/) for more information.\n\n![django-typer example](https://raw.githubusercontent.com/bckohan/django-typer/main/doc/source/_static/img/closepoll_example.gif)\n\n## Installation\n\n1. Clone django-typer from GitHub or install a release off [PyPI](https://pypi.org/project/django-typer/):\n\n   ```bash\n   pip install django-typer\n   ```\n\n   [rich](https://rich.readthedocs.io/en/latest/) is a powerful library for rich text and beautiful formatting in the terminal. It is not required but highly recommended for the best experience:\n\n   ```bash\n   pip install \"django-typer[rich]\"\n   ```\n\n2. Add `django_typer` to your `INSTALLED_APPS` setting:\n\n   ```python\n   INSTALLED_APPS = [\n       ...\n       'django_typer',\n   ]\n   ```\n\n*You only need to install django_typer as an app if you want to use the shell completion command to enable tab-completion or if you would like django-typer to install [rich traceback rendering](https://django-typer.readthedocs.io/en/latest/howto.html#configure-rich-stack-traces) for you - which it does by default if rich is also installed.*\n\n## Basic Example\n\nFor example, TyperCommands can be a very simple drop-in replacement for BaseCommands. All of the documented features of [BaseCommand](https://docs.djangoproject.com/en/stable/howto/custom-management-commands/#django.core.management.BaseCommand) work!\n\n```python\nfrom django_typer import TyperCommand\n\nclass Command(TyperCommand):\n    def handle(self, arg1: str, arg2: str, arg3: float = 0.5, arg4: int = 1):\n        \"\"\"\n        A basic command that uses Typer\n        \"\"\"\n```\n\n![Basic Example](https://raw.githubusercontent.com/bckohan/django-typer/main/django_typer/examples/helps/basic.svg)\n\n## Multiple Subcommands Example\n\n\n\nCommands with multiple subcommands can be defined:\n\n```python\n   import typing as t\n\n   from django.utils.translation import gettext_lazy as _\n   from typer import Argument\n\n   from django_typer import TyperCommand, command\n\n\n   class Command(TyperCommand):\n      \"\"\"\n      A command that defines subcommands.\n      \"\"\"\n\n      @command()\n      def create(\n         self,\n         name: t.Annotated[str, Argument(help=_(\"The name of the object to create.\"))],\n      ):\n         \"\"\"\n         Create an object.\n         \"\"\"\n\n      @command()\n      def delete(\n         self, id: t.Annotated[int, Argument(help=_(\"The id of the object to delete.\"))]\n      ):\n         \"\"\"\n         Delete an object.\n         \"\"\"\n\n```\n\n![Multiple Subcommands Example](https://raw.githubusercontent.com/bckohan/django-typer/main/django_typer/examples/helps/multi.svg)\n![Multiple Subcommands Example - create](https://raw.githubusercontent.com/bckohan/django-typer/main/django_typer/examples/helps/multi_create.svg)\n![Multiple Subcommands Example - delete](https://raw.githubusercontent.com/bckohan/django-typer/main/django_typer/examples/helps/multi_delete.svg)\n\n## Grouping and Hierarchies Example\n\nMore 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:\n\n```bash\n./manage.py hierarchy math --precision 5 divide 10 2.1\n./manage.py hierarchy math multiply 10 2\n```\n\n```python\n   import typing as t\n   from functools import reduce\n\n   from django.utils.translation import gettext_lazy as _\n   from typer import Argument, Option\n\n   from django_typer import TyperCommand, group\n\n\n   class Command(TyperCommand):\n\n      help = _(\"A more complex command that defines a hierarchy of subcommands.\")\n\n      precision = 2\n\n      @group(help=_(\"Do some math at the given precision.\"))\n      def math(\n         self,\n         precision: t.Annotated[\n            int, Option(help=_(\"The number of decimal places to output.\"))\n         ] = precision,\n      ):\n         self.precision = precision\n\n      @math.command(help=_(\"Multiply the given numbers.\"))\n      def multiply(\n         self,\n         numbers: t.Annotated[\n            t.List[float], Argument(help=_(\"The numbers to multiply\"))\n         ],\n      ):\n         return f\"{reduce(lambda x, y: x * y, [1, *numbers]):.{self.precision}f}\"\n\n      @math.command()\n      def divide(\n         self,\n         numerator: t.Annotated[float, Argument(help=_(\"The numerator\"))],\n         denominator: t.Annotated[float, Argument(help=_(\"The denominator\"))],\n         floor: t.Annotated[bool, Option(help=_(\"Use floor division\"))] = False,\n      ):\n         \"\"\"\n         Divide the given numbers.\n         \"\"\"\n         if floor:\n               return str(numerator // denominator)\n         return f\"{numerator / denominator:.{self.precision}f}\"\n\n```\n\n![Grouping and Hierarchies Example](https://raw.githubusercontent.com/bckohan/django-typer/main/django_typer/examples/helps/hierarchy.svg)\n![Grouping and Hierarchies Example - math](https://raw.githubusercontent.com/bckohan/django-typer/main/django_typer/examples/helps/hierarchy_math.svg)\n![Grouping and Hierarchies Example - math multiply](https://raw.githubusercontent.com/bckohan/django-typer/main/django_typer/examples/helps/hierarchy_math_multiply.svg)\n![Grouping and Hierarchies Example - math divide](https://raw.githubusercontent.com/bckohan/django-typer/main/django_typer/examples/helps/hierarchy_math_divide.svg)\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Use Typer to define the CLI for your Django management commands.",
    "version": "1.1.1",
    "project_urls": {
        "Homepage": "https://django-typer.readthedocs.io",
        "Repository": "https://github.com/bckohan/django-typer"
    },
    "split_keywords": [
        "django",
        " cli",
        " management",
        " typer",
        " commands"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "cca0047e95ac826db4cf72a5937af102f92bec305e3e6cf39c0e73b52d3d1b34",
                "md5": "3eb401088a41b5bc6afa95f6bb73534b",
                "sha256": "cd92d0e4ed8940c17c575e5c81caa52b623f88b13ca31f0a3b716779408c21ff"
            },
            "downloads": -1,
            "filename": "django_typer-1.1.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "3eb401088a41b5bc6afa95f6bb73534b",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0,>=3.8",
            "size": 44625,
            "upload_time": "2024-04-11T18:50:12",
            "upload_time_iso_8601": "2024-04-11T18:50:12.672577Z",
            "url": "https://files.pythonhosted.org/packages/cc/a0/047e95ac826db4cf72a5937af102f92bec305e3e6cf39c0e73b52d3d1b34/django_typer-1.1.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "565f2f7920e57f655461b491e85416a6054901469660c8d03d0c6aa4af1d0adc",
                "md5": "9a8df2d12fef6820d4479ac9d0fd6a38",
                "sha256": "1626fc8a8d718071fa5566d8dcaa5ce4df9663858daa18d1c7a0bdac1d63b2f4"
            },
            "downloads": -1,
            "filename": "django_typer-1.1.1.tar.gz",
            "has_sig": false,
            "md5_digest": "9a8df2d12fef6820d4479ac9d0fd6a38",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0,>=3.8",
            "size": 43938,
            "upload_time": "2024-04-11T18:50:14",
            "upload_time_iso_8601": "2024-04-11T18:50:14.787892Z",
            "url": "https://files.pythonhosted.org/packages/56/5f/2f7920e57f655461b491e85416a6054901469660c8d03d0c6aa4af1d0adc/django_typer-1.1.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-04-11 18:50:14",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "bckohan",
    "github_project": "django-typer",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "django-typer"
}
        
Elapsed time: 0.22867s