编写自定义 django-admin 的命令
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/
- commands/
- _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))
注解
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',
- 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, management commands are executed with the current active locale.
If, for some reason, your custom management command must run without an activelocale (for example, to prevent translated content from being inserted intothe database), deactivate translations using the @no_translations
decorator on your handle()
method:
- from django.core.management.base import BaseCommand, no_translations
- class Command(BaseCommand):
- ...
- @no_translations
- def handle(self, *args, **options):
- ...
Since translation deactivation requires access to configured settings, thedecorator can't be used for commands that work without configured settings.
Changed in Django 2.1:
The @no_translations
decorator is new. In older versions, translationsare deactivated before running a command unless the command'sleave_locale_alone
attribute (now removed) is set to True
.
测试中
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
[源代码] - 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
.- 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.
createparser
(_prog_name, subcommand, **kwargs)[源代码]- Returns a
CommandParser
instance, which is anArgumentParser
subclass with a few customizations forDjango.
You can customize the instance by overriding this method and callingsuper()
with kwargs
of ArgumentParser
parameters.
Changed in Django 2.2:kwargs
was added.
BaseCommand.
addarguments
(_parser)[源代码]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
()[源代码]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)[源代码]- 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)[源代码]- 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)[源代码]- 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
[源代码] - 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.