Reusing django code auto-reload functionality for custom management commands
Asked Answered
U

2

10

I love how django server auto-reloads itself on code change, so that no restarting the server is required.

We currently use django custom management commands that may take a very long time to complete.

Is there any way we can use the auto-reloading feature of the django server for our management command?

For example, if the change of the underlying django codebase is detected, the command reloads itself and resumes execution of the very long (stateless) loop.

Unamerican answered 7/6, 2011 at 21:11 Comment(0)
S
5

Checkout the way runserver (specifically the run method) does it with the django.utils.autoreload module. You'll want to copy this pattern with your custom command.

Supercool answered 7/6, 2011 at 21:31 Comment(0)
W
13

Whatever your management command is doing, abstract that to a single function and call that function using django.utils.autoreload.main

from django.utils import autoreload

def do_something(*args, **kwargs):
    # management command logic


class Command(BaseCommand):

    def handle(self, *args, **options):
        self.stdout('This command auto reloads. No need to restart...')
        autoreload.main(do_something, args=None, kwargs=None)

For django 2.2 or above use

        autoreload.run_with_reloader(do_something, args=None, kwargs=None)
Wixted answered 6/10, 2016 at 6:39 Comment(1)
autoreload.main() is gone now as of github.com/django/django/commit/…Hexad
S
5

Checkout the way runserver (specifically the run method) does it with the django.utils.autoreload module. You'll want to copy this pattern with your custom command.

Supercool answered 7/6, 2011 at 21:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.