Writing custom django-admin commands

Applications can register their own actions with manage.py. For example,you might want to add a manage.py action for a Django app that you'redistributing. In this document, we will be building a custom closepollcommand for the polls application from thetutorial.

To do this, just add a management/commands directory to the application.Django will register a manage.py command for each Python module in thatdirectory whose name doesn't begin with an underscore. For example:

  1. polls/
  2. __init__.py
  3. models.py
  4. management/
  5. __init__.py
  6. commands/
  7. __init__.py
  8. _private.py
  9. closepoll.py
  10. tests.py
  11. views.py

In this example, the closepoll command will be made available to any projectthat includes the polls application in INSTALLED_APPS.

The _private.py module will not be available as a management command.

The closepoll.py module has only one requirement — it must define a classCommand that extends BaseCommand or one of itssubclasses.

独一无二的脚本

Custom management commands are especially useful for running standalonescripts or for scripts that are periodically executed from the UNIX crontabor from Windows scheduled tasks control panel.

To implement the command, edit polls/management/commands/closepoll.py tolook like this:

  1. from django.core.management.base import BaseCommand, CommandError
  2. from polls.models import Question as Poll
  3.  
  4. class Command(BaseCommand):
  5. help = 'Closes the specified poll for voting'
  6.  
  7. def add_arguments(self, parser):
  8. parser.add_argument('poll_id', nargs='+', type=int)
  9.  
  10. def handle(self, *args, **options):
  11. for poll_id in options['poll_id']:
  12. try:
  13. poll = Poll.objects.get(pk=poll_id)
  14. except Poll.DoesNotExist:
  15. raise CommandError('Poll "%s" does not exist' % poll_id)
  16.  
  17. poll.opened = False
  18. poll.save()
  19.  
  20. self.stdout.write(self.style.SUCCESS('Successfully closed poll "%s"' % poll_id))

Note

When you are using management commands and wish to provide consoleoutput, you should write to self.stdout and self.stderr,instead of printing to stdout and stderr directly. Byusing these proxies, it becomes much easier to test your customcommand. Note also that you don't need to end messages with a newlinecharacter, it will be added automatically, unless you specify the endingparameter:

  1. self.stdout.write("Unterminated line", ending='')

The new custom command can be called using python manage.py closepoll<poll_id>.

The handle() method takes one or more poll_ids and sets poll.openedto False for each one. If the user referenced any nonexistent polls, aCommandError is raised. The poll.opened attribute does not exist inthe tutorial and was added topolls.models.Question for this example.

接受可选参数

The same closepoll could be easily modified to delete a given poll insteadof closing it by accepting additional command line options. These customoptions can be added in the add_arguments() method like this:

  1. class Command(BaseCommand):
  2. def add_arguments(self, parser):
  3. # Positional arguments
  4. parser.add_argument('poll_id', nargs='+', type=int)
  5.  
  6. # Named (optional) arguments
  7. parser.add_argument(
  8. '--delete',
  9. action='store_true',
  10. dest='delete',
  11. help='Delete poll instead of closing it',
  12. )
  13.  
  14. def handle(self, *args, **options):
  15. # ...
  16. if options['delete']:
  17. poll.delete()
  18. # ...

The option (delete in our example) is available in the options dictparameter of the handle method. See the argparse Python documentationfor more about add_argument usage.

In addition to being able to add custom command line options, allmanagement commands can accept some default optionssuch as —verbosity and —traceback.

Management commands and locales

By default, the BaseCommand.execute() method deactivates translationsbecause some commands shipped with Django perform several tasks (for example,user-facing content rendering and database population) that require aproject-neutral string language.

If, for some reason, your custom management command needs to use a fixed locale,you should manually activate and deactivate it in yourhandle() method using the functions provided by the I18Nsupport code:

  1. from django.core.management.base import BaseCommand, CommandError
  2. from django.utils import translation
  3.  
  4. class Command(BaseCommand):
  5. ...
  6.  
  7. def handle(self, *args, **options):
  8.  
  9. # Activate a fixed locale, e.g. Russian
  10. translation.activate('ru')
  11.  
  12. # Or you can activate the LANGUAGE_CODE # chosen in the settings:
  13. from django.conf import settings
  14. translation.activate(settings.LANGUAGE_CODE)
  15.  
  16. # Your command logic here
  17. ...
  18.  
  19. translation.deactivate()

Another need might be that your command simply should use the locale set insettings and Django should be kept from deactivating it. You can achieveit by using the BaseCommand.leave_locale_alone option.

When working on the scenarios described above though, take into account thatsystem management commands typically have to be very careful about running innon-uniform locales, so you might need to:

  • Make sure the USE_I18N setting is always True when runningthe command (this is a good example of the potential problems stemmingfrom a dynamic runtime environment that Django commands avoid offhand bydeactivating translations).
  • Review the code of your command and the code it calls for behavioraldifferences when locales are changed and evaluate its impact onpredictable behavior of your command.

测试中

Information on how to test custom management commands can be found in thetesting docs.

覆盖命令

Django 先注册内置命令, 然后按相反的顺序在 INSTALLED_APPS 查找命令. 在查找时, 如果一个命令和已注册的命令重名, 这个新发现的命令会覆盖第一个命令.

换句话说, 为了覆盖一个命令, 新命令必须有同样的名字并且它的 app 在 INSTALLED_APPS 中必须排在被覆盖命令 app 的前面.

Management commands from third-party apps that have been unintentionallyoverridden can be made available under a new name by creating a new command inone of your project's apps (ordered before the third-party app inINSTALLED_APPS) which imports the Command of the overriddencommand.

命令对象

  • class BaseCommand[source]
  • The base class from which all management commands ultimately derive.

Use this class if you want access to all of the mechanisms whichparse the command-line arguments and work out what code to call inresponse; if you don't need to change any of that behavior,consider using one of its subclasses.

Subclassing the BaseCommand class requires that you implement thehandle() method.

属性

All attributes can be set in your derived class and can be used inBaseCommand’s subclasses.

  • BaseCommand.help
  • A short description of the command, which will be printed in thehelp message when the user runs the commandpython manage.py help <command>.

  • BaseCommand.missing_args_message

  • If your command defines mandatory positional arguments, you can customizethe message error returned in the case of missing arguments. The default isoutput by argparse ("too few arguments").

  • BaseCommand.output_transaction

  • A boolean indicating whether the command outputs SQL statements; ifTrue, the output will automatically be wrapped with BEGIN; andCOMMIT;. Default value is False.

  • BaseCommand.requires_migrations_checks

  • A boolean; if True, the command prints a warning if the set ofmigrations on disk don't match the migrations in the database. A warningdoesn't prevent the command from executing. Default value is False.

  • BaseCommand.requires_system_checks

  • A boolean; if True, the entire Django project will be checked forpotential problems prior to executing the command. Default value is True.

  • BaseCommand.leave_locale_alone

  • A boolean indicating whether the locale set in settings should be preservedduring the execution of the command instead of translations beingdeactivated.

默认值是 False

Make sure you know what you are doing if you decide to change the value ofthis option in your custom command if it creates database content thatis locale-sensitive and such content shouldn't contain any translations(like it happens e.g. with django.contrib.auth permissions) asactivating any locale might cause unintended effects. See the Managementcommands and locales section above for further details.

  • BaseCommand.style
  • An instance attribute that helps create colored output when writing tostdout or stderr. For example:
  1. self.stdout.write(self.style.SUCCESS('...'))

See Syntax coloring to learn how to modify the color palette and tosee the available styles (use uppercased versions of the "roles" describedin that section).

If you pass the —no-color option when running your command, allself.style() calls will return the original string uncolored.

方法

BaseCommand has a few methods that can be overridden but onlythe handle() method must be implemented.

Implementing a constructor in a subclass

If you implement init in your subclass of BaseCommand,you must call BaseCommand’s init:

  1. class Command(BaseCommand):
  2. def __init__(self, *args, **kwargs):
  3. super().__init__(*args, **kwargs)
  4. # ...
  • BaseCommand.addarguments(_parser)[source]
  • Entry point to add parser arguments to handle command line arguments passedto the command. Custom commands should override this method to add bothpositional and optional arguments accepted by the command. Callingsuper() is not needed when directly subclassing BaseCommand.

  • BaseCommand.get_version()[source]

  • Returns the Django version, which should be correct for all built-in Djangocommands. User-supplied commands can override this method to return theirown version.

  • BaseCommand.execute(*args, **options)[source]

  • Tries to execute this command, performing system checks if needed (ascontrolled by the requires_system_checks attribute). If the commandraises a CommandError, it's intercepted and printed to stderr.

在你的代码中调用管理命令

execute() should not be called directly from your code to execute acommand. Use call_command() instead.

  • BaseCommand.handle(*args, **options)[source]
  • The actual logic of the command. Subclasses must implement this method.

It may return a string which will be printed to stdout (wrappedby BEGIN; and COMMIT; if output_transaction is True).

  • BaseCommand.check(app_configs=None, tags=None, display_num_errors=False)[source]
  • Uses the system check framework to inspect the entire Django project forpotential problems. Serious problems are raised as a CommandError;warnings are output to stderr; minor notifications are output to stdout.

If app_configs and tags are both None, all system checks areperformed. tags can be a list of check tags, like compatibility ormodels.

BaseCommand subclasses

  • class AppCommand
  • A management command which takes one or more installed application labels asarguments, and does something with each of them.

Rather than implementing handle(), subclasses mustimplement handle_app_config(), which will be called once foreach application.

  • AppCommand.handleapp_config(_app_config, **options)
  • Perform the command's actions for app_config, which will be anAppConfig instance corresponding to an applicationlabel given on the command line.

  • class LabelCommand

  • A management command which takes one or more arbitrary arguments (labels) onthe command line, and does something with each of them.

Rather than implementing handle(), subclasses must implementhandle_label(), which will be called once for each label.

  • LabelCommand.label
  • A string describing the arbitrary arguments passed to the command. Thestring is used in the usage text and error messages of the command.Defaults to 'label'.

  • LabelCommand.handlelabel(_label, **options)

  • Perform the command's actions for label, which will be the string asgiven on the command line.

命令异常

  • exception CommandError[source]
  • Exception class indicating a problem while executing a management command.

If this exception is raised during the execution of a management command from acommand line console, it will be caught and turned into a nicely-printed errormessage to the appropriate output stream (i.e., stderr); as a result, raisingthis exception (with a sensible description of the error) is the preferred wayto indicate that something has gone wrong in the execution of a command.

If a management command is called from code throughcall_command(), it's up to you to catch theexception when needed.