Jak napisać własne komendy django-admin
¶
Aplikacje mogą rejestrować swoje własne akcje w manage.py
. Na przykład mógłbyś chcieć dodać akcję manage.py
dla aplikacji Django, którą udostępniasz. W tym dokumencie będziemy budować własną komendę closepoll
dla aplikacji polls
z samouczka.
To do this, add a management/commands
directory to the application. Django
will register a manage.py
command for each Python module in that directory
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
W tym przykładzie komenda closepoll
stanie się dostępna dla każdego projektu, który umieści aplikację polls
w INSTALLED_APPS
.
Moduł _private.py
nie będzie dostępny jako komenda zarządzania.
Jest tylko jedno wymaganie dla closepoll.py
– musi definiować klasę Command
, która dziedziczy po BaseCommand
lub jednej z jej podklas.
Samodzielne skrypty
Własne komendy zarządcze są szczególnie przydatne w odpalaniu samodzielnych skryptów lub skryptów wykonywanych cyklicznie z tabeli programu cron Uniksa lub z panelu kontrolnego harmonogramu zadań Windows.
Aby zaimplementować komendę, zmień polls/management/commands/closepoll.py
, aby wyglądał w ten sposób:
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_ids", nargs="+", type=int)
def handle(self, *args, **options):
for poll_id in options["poll_ids"]:
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)
)
Informacja
Gdy używasz komend zarządczych i chcesz pisać na konsolę, powinieneś pisać na self.stdout
i self.stderr
, zamiast drukować bezpośrednio na stdout
i stderr
. Przy użyciu tych proxy, testowanie twojej komendy staje się dużo prostsze. Zwróć też uwagę, że nie potrzebujesz kończyć wiadomości znakiem końca linii. Zostanie on dodany automatycznie, chyba że podasz parametr ending
:
self.stdout.write("Unterminated line", ending="")
The new custom command can be called using python manage.py closepoll
<poll_ids>
.
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, a
CommandError
is raised. The poll.opened
attribute does not exist in
the tutorial and was added to
polls.models.Question
for this example.
Akceptowanie opcjonalnych argumentów¶
The same closepoll
could be easily modified to delete a given poll instead
of closing it by accepting additional command line options. These custom
options can be added in the add_arguments()
method like this:
class Command(BaseCommand):
def add_arguments(self, parser):
# Positional arguments
parser.add_argument("poll_ids", 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 dict
parameter of the handle method. See the argparse
Python documentation
for more about add_argument
usage.
In addition to being able to add custom command line options, all
management commands can accept some default options
such 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 active
locale (for example, to prevent translated content from being inserted into
the 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, the decorator can’t be used for commands that work without configured settings.
Testowanie¶
Information on how to test custom management commands can be found in the testing docs.
Nadpisywanie komend¶
Django registers the built-in commands and then searches for commands in
INSTALLED_APPS
in reverse. During the search, if a command name
duplicates an already registered command, the newly discovered command
overrides the first.
In other words, to override a command, the new command must have the same name
and its app must be before the overridden command’s app in
INSTALLED_APPS
.
Management commands from third-party apps that have been unintentionally
overridden can be made available under a new name by creating a new command in
one of your project’s apps (ordered before the third-party app in
INSTALLED_APPS
) which imports the Command
of the overridden
command.
Obiekty komend¶
-
class
BaseCommand
¶
The base class from which all management commands ultimately derive.
Use this class if you want access to all of the mechanisms which parse the command-line arguments and work out what code to call in response; 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 the
handle()
method.
Atrybuty¶
All attributes can be set in your derived class and can be used in
BaseCommand
’s subclasses.
-
BaseCommand.
help
¶ A short description of the command, which will be printed in the help message when the user runs the command
python manage.py help <command>
.
-
BaseCommand.
missing_args_message
¶ If your command defines mandatory positional arguments, you can customize the message error returned in the case of missing arguments. The default is output by
argparse
(„too few arguments”).
-
BaseCommand.
output_transaction
¶ A boolean indicating whether the command outputs SQL statements; if
True
, the output will automatically be wrapped withBEGIN;
andCOMMIT;
. Default value isFalse
.
-
BaseCommand.
requires_migrations_checks
¶ A boolean; if
True
, the command prints a warning if the set of migrations on disk don’t match the migrations in the database. A warning doesn’t prevent the command from executing. Default value isFalse
.
-
BaseCommand.
requires_system_checks
¶ A list or tuple of tags, e.g.
[Tags.staticfiles, Tags.models]
. System checks registered in the chosen tags will be checked for errors prior to executing the command. The value'__all__'
can be used to specify that all system checks should be performed. Default value is'__all__'
.
-
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 to see the available styles (use uppercased versions of the „roles” described in that section).
If you pass the
--no-color
option when running your command, allself.style()
calls will return the original string uncolored.
-
BaseCommand.
suppressed_base_arguments
¶ The default command options to suppress in the help output. This should be a set of option names (e.g.
'--verbosity'
). The default values for the suppressed options are still passed.
Metody¶
BaseCommand
has a few methods that can be overridden but only
the 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.
create_parser
(prog_name, subcommand, **kwargs)¶ Returns a
CommandParser
instance, which is anArgumentParser
subclass with a few customizations for Django.You can customize the instance by overriding this method and calling
super()
withkwargs
ofArgumentParser
parameters.
-
BaseCommand.
add_arguments
(parser)¶ Entry point to add parser arguments to handle command line arguments passed to the command. Custom commands should override this method to add both positional 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 Django commands. User-supplied commands can override this method to return their own version.
-
BaseCommand.
execute
(*args, **options)¶ Tries to execute this command, performing system checks if needed (as controlled by the
requires_system_checks
attribute). If the command raises aCommandError
, it’s intercepted and printed tostderr
.
Wywoływanie komendy zarządzającej w Twoim kodzie
execute()
should not be called directly from your code to execute a
command. 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
(wrapped byBEGIN;
andCOMMIT;
ifoutput_transaction
isTrue
).
-
BaseCommand.
check
(app_configs=None, tags=None, display_num_errors=False)¶ Uses the system check framework to inspect the entire Django project for potential problems. Serious problems are raised as a
CommandError
; warnings are output tostderr
; minor notifications are output tostdout
.If
app_configs
andtags
are bothNone
, all system checks are performed.tags
can be a list of check tags, likecompatibility
ormodels
.
BaseCommand
subclasses¶
-
class
AppCommand
¶
A management command which takes one or more installed application labels as arguments, and does something with each of them.
Rather than implementing handle()
, subclasses must
implement handle_app_config()
, which will be called once for
each application.
-
AppCommand.
handle_app_config
(app_config, **options)¶ Perform the command’s actions for
app_config
, which will be anAppConfig
instance corresponding to an application label given on the command line.
-
class
LabelCommand
¶
A management command which takes one or more arbitrary arguments (labels) on the command line, and does something with each of them.
Rather than implementing handle()
, subclasses must implement
handle_label()
, which will be called once for each label.
-
LabelCommand.
label
¶ A string describing the arbitrary arguments passed to the command. The string is used in the usage text and error messages of the command. Defaults to
'label'
.
-
LabelCommand.
handle_label
(label, **options)¶ Wykonuje działania komendy dla etykiety``label``, którą będzie łańcuch podany w linii komend.
Wyjątki komend¶
-
exception
CommandError
(returncode=1)¶
Klasa wyjątków wskazująca na problem podczas wykonywania polecenia zarządzania.
If this exception is raised during the execution of a management command from a
command line console, it will be caught and turned into a nicely-printed error
message to the appropriate output stream (i.e., stderr
); as a result,
raising this exception (with a sensible description of the error) is the
preferred way to indicate that something has gone wrong in the execution of a
command. It accepts the optional returncode
argument to customize the exit
status for the management command to exit with, using sys.exit()
.
If a management command is called from code through
call_command()
, it’s up to you to catch the
exception when needed.