There is a way to add features to an existing django command?

后端 未结 3 503
余生分开走
余生分开走 2020-12-14 20:20

I want to run a command just before the a django command is started.

For example:

$ python manage.py runserver
Validating models...

0 errors found
D         


        
3条回答
  •  萌比男神i
    2020-12-14 20:44

    Just realize that you can override the commands just easily as making an app with a command with the same name.

    So I create an app and create a file with the same name as runserver, and later on that extend the runserver base class to add a new feature before it runs.

    For example, I want to run the command $ compass watch, just before runserver starts and keep it running along runserver execution.

    """
    Start $compass watch, command when you do $python manage.py runserver
    
    file: main/management/commands/runserver.py
    
    Add ´main´ app to the last of the installed apps
    """
    
    from optparse import make_option
    import os
    import subprocess
    
    from django.core.management.base import BaseCommand, CommandError
    from django.core.management.commands.runserver import BaseRunserverCommand
    from django.conf import settings
    
    class Command(BaseRunserverCommand):
        option_list = BaseRunserverCommand.option_list + (
            make_option('--adminmedia', dest='admin_media_path', default='',
                help='Specifies the directory from which to serve admin media.'),
            make_option('--watch', dest='compass_project_path', default=settings.MEDIA_ROOT,
                help='Specifies the project directory for compass.'),
        )
    
        def inner_run(self, *args, **options):
            self.compass_project_path = options.get('compass_project_path', settings.MEDIA_ROOT)
    
            self.stdout.write("Starting the compass watch command for %r\n" % self.compass_project_path)
            self.compass_pid = subprocess.Popen(["compass watch %s" % self.compass_project_path],
                shell=True,
                stdin=subprocess.PIPE,
                stdout=self.stdout,
                stderr=self.stderr)
            self.stdout.write("Compas watch process on %r\n" % self.compass_pid.pid)
    
            super(Command, self).inner_run(*args, **options)
    

    This works just fine.

    Look at https://docs.djangoproject.com/en/dev/howto/custom-management-commands/ for more details about django commands

    Hope someone find this helpful

提交回复
热议问题