custom-management-commands.txt 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. .. _howto-custom-management-commands:
  2. ====================================
  3. Writing custom django-admin commands
  4. ====================================
  5. .. versionadded:: 1.0
  6. Applications can register their own actions with ``manage.py``. For example,
  7. you might want to add a ``manage.py`` action for a Django app that you're
  8. distributing. In this document, we will be building a custom ``closepoll``
  9. command for the ``polls`` application from the
  10. :ref:`tutorial<intro-tutorial01>`.
  11. To do this, just add a ``management/commands`` directory to the application.
  12. Each Python module in that directory will be auto-discovered and registered as
  13. a command that can be executed as an action when you run ``manage.py``::
  14. polls/
  15. __init__.py
  16. models.py
  17. management/
  18. __init__.py
  19. commands/
  20. __init__.py
  21. closepoll.py
  22. tests.py
  23. views.py
  24. In this example, the ``closepoll`` command will be made available to any project
  25. that includes the ``polls`` application in :setting:`INSTALLED_APPS`.
  26. The ``closepoll.py`` module has only one requirement -- it must define a class
  27. ``Command`` that extends :class:`BaseCommand` or one of its
  28. :ref:`subclasses<ref-basecommand-subclasses>`.
  29. .. admonition:: Standalone scripts
  30. Custom management commands are especially useful for running standalone
  31. scripts or for scripts that are periodically executed from the UNIX crontab
  32. or from Windows scheduled tasks control panel.
  33. To implement the command, edit ``polls/management/commands/closepoll.py`` to
  34. look like this:
  35. .. code-block:: python
  36. from django.core.management.base import BaseCommand, CommandError
  37. from example.polls.models import Poll
  38. class Command(BaseCommand):
  39. args = '<poll_id poll_id ...>'
  40. help = 'Closes the specified poll for voting'
  41. def handle(self, *args, **options):
  42. for poll_id in args:
  43. try:
  44. poll = Poll.objects.get(pk=int(poll_id))
  45. except Poll.DoesNotExist:
  46. raise CommandError('Poll "%s" does not exist' % poll_id)
  47. poll.opened = False
  48. poll.save()
  49. print 'Successfully closed poll "%s"' % poll_id
  50. The new custom command can be called using ``python manage.py closepoll
  51. <poll_id>``.
  52. The ``handle()`` method takes zero or more ``poll_ids`` and sets ``poll.opened``
  53. to ``False`` for each one. If the user referenced any nonexistant polls, a
  54. :class:`CommandError` is raised. The ``poll.opened`` attribute does not exist
  55. in the :ref:`tutorial<intro-tutorial01>` and was added to
  56. ``polls.models.Poll`` for this example.
  57. The same ``closepoll`` could be easily modified to delete a given poll instead
  58. of closing it by accepting additional command line options. These custom options
  59. must be added to :attr:`~BaseCommand.option_list` like this:
  60. .. code-block:: python
  61. from optparse import make_option
  62. class Command(BaseCommand):
  63. option_list = BaseCommand.option_list + (
  64. make_option('--delete',
  65. action='store_true',
  66. dest='delete',
  67. default=False,
  68. help='Delete poll instead of closing it'),
  69. )
  70. # ...
  71. In addition to being able to add custom command line options, all
  72. :ref:`management commands<ref-django-admin>` can accept some
  73. default options such as :djadminopt:`--verbosity` and :djadminopt:`--traceback`.
  74. Command objects
  75. ===============
  76. .. class:: BaseCommand
  77. The base class from which all management commands ultimately derive.
  78. Use this class if you want access to all of the mechanisms which
  79. parse the command-line arguments and work out what code to call in
  80. response; if you don't need to change any of that behavior,
  81. consider using one of its :ref:`subclasses<ref-basecommand-subclasses>`.
  82. Subclassing the :class:`BaseCommand` class requires that you implement the
  83. :meth:`~BaseCommand.handle` method.
  84. Attributes
  85. ----------
  86. All attributes can be set in your derived class and can be used in
  87. :class:`BaseCommand`'s :ref:`subclasses<ref-basecommand-subclasses>`.
  88. .. attribute:: BaseCommand.args
  89. A string listing the arguments accepted by the command,
  90. suitable for use in help messages; e.g., a command which takes
  91. a list of application names might set this to '<appname
  92. appname ...>'.
  93. .. attribute:: BaseCommand.can_import_settings
  94. A boolean indicating whether the command needs to be able to
  95. import Django settings; if ``True``, ``execute()`` will verify
  96. that this is possible before proceeding. Default value is
  97. ``True``.
  98. .. attribute:: BaseCommand.help
  99. A short description of the command, which will be printed in the
  100. help message when the user runs the command
  101. ``python manage.py help <command>``.
  102. .. attribute:: BaseCommand.option_list
  103. This is the list of ``optparse`` options which will be fed
  104. into the command's ``OptionParser`` for parsing arguments.
  105. .. attribute:: BaseCommand.output_transaction
  106. A boolean indicating whether the command outputs SQL
  107. statements; if ``True``, the output will automatically be
  108. wrapped with ``BEGIN;`` and ``COMMIT;``. Default value is
  109. ``False``.
  110. .. attribute:: BaseCommand.requires_model_validation
  111. A boolean; if ``True``, validation of installed models will be
  112. performed prior to executing the command. Default value is
  113. ``True``. To validate an individual application's models
  114. rather than all applications' models, call
  115. :meth:`~BaseCommand.validate` from :meth:`~BaseCommand.handle`.
  116. Methods
  117. -------
  118. :class:`BaseCommand` has a few methods that can be overridden but only
  119. the :meth:`~BaseCommand.handle` method must be implemented.
  120. .. admonition:: Implementing a constructor in a subclass
  121. If you implement ``__init__`` in your subclass of :class:`BaseCommand`,
  122. you must call :class:`BaseCommand`'s ``__init__``.
  123. .. code-block:: python
  124. class Command(BaseCommand):
  125. def __init__(self, *args, **kwargs):
  126. super(Command, self).__init__(*args, **kwargs)
  127. # ...
  128. .. method:: BaseCommand.get_version()
  129. Return the Django version, which should be correct for all
  130. built-in Django commands. User-supplied commands can
  131. override this method to return their own version.
  132. .. method:: BaseCommand.execute(*args, **options)
  133. Try to execute this command, performing model validation if
  134. needed (as controlled by the attribute
  135. :attr:`requires_model_validation`). If the command raises a
  136. :class:`CommandError`, intercept it and print it sensibly to
  137. stderr.
  138. .. method:: BaseCommand.handle(*args, **options)
  139. The actual logic of the command. Subclasses must implement this method.
  140. .. _ref-basecommand-subclasses:
  141. BaseCommand subclasses
  142. ----------------------
  143. .. class:: AppCommand
  144. A management command which takes one or more installed application
  145. names as arguments, and does something with each of them.
  146. Rather than implementing :meth:`~BaseCommand.handle`, subclasses must implement
  147. :meth:`~AppCommand.handle_app`, which will be called once for each application.
  148. .. method:: AppCommand.handle_app(app, **options)
  149. Perform the command's actions for ``app``, which will be the
  150. Python module corresponding to an application name given on
  151. the command line.
  152. .. class:: LabelCommand
  153. A management command which takes one or more arbitrary arguments
  154. (labels) on the command line, and does something with each of
  155. them.
  156. Rather than implementing :meth:`~BaseCommand.handle`, subclasses must implement
  157. :meth:`~LabelCommand.handle_label`, which will be called once for each label.
  158. .. method:: LabelCommand.handle_label(label, **options)
  159. Perform the command's actions for ``label``, which will be the
  160. string as given on the command line.
  161. .. class:: NoArgsCommand
  162. A command which takes no arguments on the command line.
  163. Rather than implementing :meth:`~BaseCommand.handle`, subclasses must implement
  164. :meth:`~NoArgsCommand.handle_noargs`; :meth:`~BaseCommand.handle` itself is
  165. overridden to ensure no arguments are passed to the command.
  166. .. method:: NoArgsCommand.handle_noargs(**options)
  167. Perform this command's actions
  168. .. _ref-command-exceptions:
  169. Command exceptions
  170. ------------------
  171. .. class:: CommandError
  172. Exception class indicating a problem while executing a management
  173. command.
  174. If this exception is raised during the execution of a management
  175. command, it will be caught and turned into a nicely-printed error
  176. message to the appropriate output stream (i.e., stderr); as a
  177. result, raising this exception (with a sensible description of the
  178. error) is the preferred way to indicate that something has gone
  179. wrong in the execution of a command.