Extensions for using Rich with Django.

Related tags

Django django-rich
Overview

django-rich

https://img.shields.io/github/workflow/status/adamchainz/django-rich/CI/main?style=for-the-badge https://img.shields.io/badge/Coverage-100%25-success?style=for-the-badge https://img.shields.io/pypi/v/django-rich.svg?style=for-the-badge https://img.shields.io/badge/code%20style-black-000000.svg?style=for-the-badge pre-commit

Extensions for using Rich with Django.

Requirements

Python 3.6 to 3.10 supported.

Django 2.2 to 4.0 supported.


Are your tests slow? Check out my book Speed Up Your Django Tests which covers loads of best practices so you can write faster, more accurate tests.


Installation

  1. Install with pip:

    python -m pip install django-rich

Reference

django_rich.management.RichCommand

A subclass of Django’s BaseCommand class that sets its self.console to a Rich Console. The Console uses the command’s stdout argument, which defaults to sys.stdout. Colourization is enabled or disabled according to Django’s --no-color and --force-color flags.

You can use self.console like so:

from django_rich.management import RichCommand


class Command(RichCommand):
    def handle(self, *args, **options):
        self.console.print("[bold red]Alert![/bold red]")

You can customize the construction of the Console by overriding the make_rich_console class attribute. This should be a callable that returns a Console, such as a functools.partial. For example, to disable the default-on markup and highlighting flags:

from functools import partial

from django_rich.management import RichCommand
from rich.console import Console


class Command(RichCommand):
    make_rich_console = partial(Console, markup=False, highlight=False)

    def handle(self, *args, **options):
        ...
Comments
  • Added Rich Test Runner

    Added Rich Test Runner

    Hi Adam 👋

    I've made a few changes to the image shared on twitter a few days ago. I've added Color to the test output and customised the lines above and below the test headings (ft. a Django shade of green).

    I was unsure how best to test this. In my little package I created a test project (included here for demo purposes -- will need refinement) then ran it using subprocess and captured the output. I'd appreciate your guidance on how you'd like the tests approached. I saw you were using call_command but that did not seem to work for me when the command is test

    image

    opened by smithdc1 18
  • Bump actions/setup-python from 3 to 4

    Bump actions/setup-python from 3 to 4

    Bumps actions/setup-python from 3 to 4.

    Release notes

    Sourced from actions/setup-python's releases.

    v4.0.0

    What's Changed

    • Support for python-version-file input: #336

    Example of usage:

    - uses: actions/setup-python@v4
      with:
        python-version-file: '.python-version' # Read python version from a file
    - run: python my_script.py
    

    There is no default python version for this setup-python major version, the action requires to specify either python-version input or python-version-file input. If the python-version input is not specified the action will try to read required version from file from python-version-file input.

    • Use pypyX.Y for PyPy python-version input: #349

    Example of usage:

    - uses: actions/setup-python@v4
      with:
        python-version: 'pypy3.9' # pypy-X.Y kept for backward compatibility
    - run: python my_script.py
    
    • RUNNER_TOOL_CACHE environment variable is equal AGENT_TOOLSDIRECTORY: #338

    • Bugfix: create missing pypyX.Y symlinks: #347

    • PKG_CONFIG_PATH environment variable: #400

    • Added python-path output: #405 python-path output contains Python executable path.

    • Updated zeit/ncc to vercel/ncc package: #393

    • Bugfix: fixed output for prerelease version of poetry: #409

    • Made pythonLocation environment variable consistent for Python and PyPy: #418

    • Bugfix for 3.x-dev syntax: #417

    • Other improvements: #318 #396 #384 #387 #388

    Update actions/cache version to 2.0.2

    In scope of this release we updated actions/cache package as the new version contains fixes related to GHES 3.5 (actions/setup-python#382)

    Add "cache-hit" output and fix "python-version" output for PyPy

    This release introduces new output cache-hit (actions/setup-python#373) and fix python-version output for PyPy (actions/setup-python#365)

    The cache-hit output contains boolean value indicating that an exact match was found for the key. It shows that the action uses already existing cache or not. The output is available only if cache is enabled.

    ... (truncated)

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    dependencies 
    opened by dependabot[bot] 0
  • Pretty install on 'manage.py shell'

    Pretty install on 'manage.py shell'

    Description

    Rich has "pretty" mode that can be installed in the plain python repl, and in ipython:

    https://rich.readthedocs.io/en/latest/introduction.html?highlight=install#rich-in-the-repl

    We could extend manage.py shell to use that automatically.

    opened by adamchainz 0
  • Add test case utility for e.g. console width

    Add test case utility for e.g. console width

    Description

    While writing a test for a RichCommand management command, I ran into trouble on the CI, because inside a Rich Table, the column headers were cropped from Maximum Value to Max….

    First, I couldn't reproduce this locally, since my console width was at about 300 characters. On the CI, however, it as just 80 chars.

    I now have a mixin for my test cases that allows me to set some console configurations:

    from contextlib import contextmanager
    from functools import partial
    from unittest import mock
    from rich.console import Console
    
    class RichConsoleMixin:
        @contextmanager
        def patch_console(self):
            with mock.patch(
                "django_rich.management.RichCommand.make_rich_console",
                partial(Console, width=200),
            ):
                yield
    

    Usage:

    class TestMyCommand(RichConsoleMixin, TestCase):
        def test_call(self):
            stdout = io.StringIO()
            with self.patch_console():
                call_command("my_command", stdout=stdout)
            out = stdout.getvalue()
            self.assertIn("Maximum Value", out)
    

    It might be convenient to have a similar mixin available as part of rich-django.

    opened by MarkusH 1
  • Added slowest test output to RichRunner.

    Added slowest test output to RichRunner.

    Hi Adam -- me again 😄

    So there's a few design choices I've made.

    The first is in the output we can give. For simplicity the test timings will only be output at the end of the test run. The cPython patch would allow them to be inlined when running verbose mode but as far as I can tell that would require folk to use a custom TestCase. That breaks the simplicity of "add a setting" to get up and running.

    The second is how you enable it. There's various options, I've currently gone with pass in --timing to get it to output, and if verbosity is increased then you get more tests. There's more complex options e.g. add a new flag e.g. --duration and allow it to pass in a value, but that adds complexity especially if this could make it's way into Django core one day. Another option I considered was to always output the slowest tests (we're capturing it anyway).

    I am hoping this is a better quality patch at the first pass than last time. I'm hopeful to see the magic green tick shortly. (I suspect Django 2.2 may have something to say about that).

    Ah, finally I think there's a few missing items in typeshed so a number of #ignores dotted about.

    image

    p.s. that regression test is slow 🕵️

    opened by smithdc1 5
  • QuerySet progress display

    QuerySet progress display

    Description

    By default Rich’s progress uses len(iterable) to get the number of objects. This is not performant, and at least QuerySet.count() could be used for querysets. Perhaps there could also be more help in a wrapper.

    opened by adamchainz 0
Owner
Adam Johnson
🦄 @django technical board member 🇬🇧 @djangolondon co-organizer ✍ AWS/Django/Python Author and Consultant
Adam Johnson
Django URL Shortener is a Django app to to include URL Shortening feature in your Django Project

Django URL Shortener Django URL Shortener is a Django app to to include URL Shortening feature in your Django Project Install this package to your Dja

Rishav Sinha 4 Nov 18, 2021
A beginner django project and also my first Django project which involves shortening of a longer URL into a short one using a unique id.

Django-URL-Shortener A beginner django project and also my first Django project which involves shortening of a longer URL into a short one using a uni

Rohini Rao 3 Aug 8, 2021
DRF_commands is a Django package that helps you to create django rest framework endpoints faster using manage.py.

DRF_commands is a Django package that helps you to create django rest framework endpoints faster using manage.py.

Mokrani Yacine 2 Sep 28, 2022
A starter template for building a backend with Django and django-rest-framework using docker with PostgreSQL as the primary DB.

Django-Rest-Template! This is a basic starter template for a backend project with Django as the server and PostgreSQL as the database. About the templ

Akshat Sharma 11 Dec 6, 2022
Django-discord-bot - Framework for creating Discord bots using Django

django-discord-bot Framework for creating Discord bots using Django Uses ASGI fo

Jamie Bliss 1 Mar 4, 2022
Django-Text-to-HTML-converter - The simple Text to HTML Converter using Django framework

Django-Text-to-HTML-converter This is the simple Text to HTML Converter using Dj

Nikit Singh Kanyal 6 Oct 9, 2022
Meta package to combine turbo-django and stimulus-django

Hotwire + Django This repository aims to help you integrate Hotwire with Django ?? Inspiration might be taken from @hotwired/hotwire-rails. We are sti

Hotwire for Django 31 Aug 9, 2022
django-reversion is an extension to the Django web framework that provides version control for model instances.

django-reversion django-reversion is an extension to the Django web framework that provides version control for model instances. Requirements Python 3

Dave Hall 2.8k Jan 2, 2023
Django-environ allows you to utilize 12factor inspired environment variables to configure your Django application.

Django-environ django-environ allows you to use Twelve-factor methodology to configure your Django application with environment variables. import envi

Daniele Faraglia 2.7k Jan 7, 2023
Rosetta is a Django application that eases the translation process of your Django projects

Rosetta Rosetta is a Django application that facilitates the translation process of your Django projects. Because it doesn't export any models, Rosett

Marco Bonetti 909 Dec 26, 2022
Cookiecutter Django is a framework for jumpstarting production-ready Django projects quickly.

Cookiecutter Django Powered by Cookiecutter, Cookiecutter Django is a framework for jumpstarting production-ready Django projects quickly. Documentati

Daniel Feldroy 10k Dec 31, 2022
Django project starter on steroids: quickly create a Django app AND generate source code for data models + REST/GraphQL APIs (the generated code is auto-linted and has 100% test coverage).

Create Django App ?? We're a Django project starter on steroids! One-line command to create a Django app with all the dependencies auto-installed AND

imagine.ai 68 Oct 19, 2022
django-quill-editor makes Quill.js easy to use on Django Forms and admin sites

django-quill-editor django-quill-editor makes Quill.js easy to use on Django Forms and admin sites No configuration required for static files! The ent

lhy 139 Dec 5, 2022
A Django chatbot that is capable of doing math and searching Chinese poet online. Developed with django, channels, celery and redis.

Django Channels Websocket Chatbot A Django chatbot that is capable of doing math and searching Chinese poet online. Developed with django, channels, c

Yunbo Shi 8 Oct 28, 2022
A handy tool for generating Django-based backend projects without coding. On the other hand, it is a code generator of the Django framework.

Django Sage Painless The django-sage-painless is a valuable package based on Django Web Framework & Django Rest Framework for high-level and rapid web

sageteam 51 Sep 15, 2022
Dockerizing Django with Postgres, Gunicorn, Nginx and Certbot. A fully Django starter project.

Dockerizing Django with Postgres, Gunicorn, Nginx and Certbot ?? Features A Django stater project with fully basic requirements for a production-ready

null 8 Jun 27, 2022
pytest-django allows you to test your Django project/applications with the pytest testing tool.

pytest-django allows you to test your Django project/applications with the pytest testing tool.

pytest-dev 1.1k Dec 14, 2022
APIs for a Chat app. Written with Django Rest framework and Django channels.

ChatAPI APIs for a Chat app. Written with Django Rest framework and Django channels. The documentation for the http end points can be found here This

Victor Aderibigbe 18 Sep 9, 2022
django-dashing is a customisable, modular dashboard application framework for Django to visualize interesting data about your project. Inspired in the dashboard framework Dashing

django-dashing django-dashing is a customisable, modular dashboard application framework for Django to visualize interesting data about your project.

talPor Solutions 703 Dec 22, 2022