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 closepoll
command 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:
- polls/
- __init__.py
- models.py
- management/
- __init__.py
- commands/
- __init__.py
- _private.py
- closepoll.py
- tests.py
- 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:
- from django.core.management.base import BaseCommand, CommandError
- from polls.models import Question as Poll
- class Command(BaseCommand):
- help = 'Closes the specified poll for voting'
- def add_arguments(self, parser):
- parser.add_argument('poll_id', nargs='+', type=int)
- def handle(self, *args, **options):
- for poll_id in options['poll_id']:
- try:
- poll = Poll.objects.get(pk=poll_id)
- except Poll.DoesNotExist:
- raise CommandError('Poll "%s" does not exist' % poll_id)
- poll.opened = False
- poll.save()
- 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 ending
parameter:
- 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.opened
to 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:
- class Command(BaseCommand):
- def add_arguments(self, parser):
- # Positional arguments
- parser.add_argument('poll_id', nargs='+', type=int)
- # Named (optional) arguments
- parser.add_argument(
- '--delete',
- action='store_true',
- dest='delete',
- help='Delete poll instead of closing it',
- )
- def handle(self, *args, **options):
- # ...
- if options['delete']:
- poll.delete()
- # ...
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:
- from django.core.management.base import BaseCommand, CommandError
- from django.utils import translation
- class Command(BaseCommand):
- ...
- def handle(self, *args, **options):
- # Activate a fixed locale, e.g. Russian
- translation.activate('ru')
- # Or you can activate the LANGUAGE_CODE # chosen in the settings:
- from django.conf import settings
- translation.activate(settings.LANGUAGE_CODE)
- # Your command logic here
- ...
- 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 alwaysTrue
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 command
python manage.py help <command>
.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").A boolean indicating whether the command outputs SQL statements; if
True
, the output will automatically be wrapped withBEGIN;
andCOMMIT;
. Default value isFalse
.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 isFalse
.A boolean; if
True
, the entire Django project will be checked forpotential problems prior to executing the command. Default value isTrue
.- 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 to
stdout
orstderr
. For example:
- 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
:
- class Command(BaseCommand):
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
- # ...
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. Calling
super()
is not needed when directly subclassingBaseCommand
.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 aCommandError
, 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.- 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'
.- 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.