custom-management-commands.txt 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. ====================================
  2. Writing custom django-admin commands
  3. ====================================
  4. Applications can register their own actions with ``manage.py``. For example,
  5. you might want to add a ``manage.py`` action for a Django app that you're
  6. distributing. In this document, we will be building a custom ``closepoll``
  7. command for the ``polls`` application from the
  8. :doc:`tutorial</intro/tutorial01>`.
  9. To do this, just add a ``management/commands`` directory to the application.
  10. Django will register a ``manage.py`` command for each Python module in that
  11. directory whose name doesn't begin with an underscore. For example::
  12. polls/
  13. __init__.py
  14. models.py
  15. management/
  16. __init__.py
  17. commands/
  18. __init__.py
  19. _private.py
  20. closepoll.py
  21. tests.py
  22. views.py
  23. In this example, the ``closepoll`` command will be made available to any project
  24. that includes the ``polls`` application in :setting:`INSTALLED_APPS`.
  25. The ``_private.py`` module will not be available as a management command.
  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 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. self.stdout.write('Successfully closed poll "%s"' % poll_id)
  50. .. note::
  51. When you are using management commands and wish to provide console
  52. output, you should write to ``self.stdout`` and ``self.stderr``,
  53. instead of printing to ``stdout`` and ``stderr`` directly. By
  54. using these proxies, it becomes much easier to test your custom
  55. command.
  56. The new custom command can be called using ``python manage.py closepoll
  57. <poll_id>``.
  58. The ``handle()`` method takes zero or more ``poll_ids`` and sets ``poll.opened``
  59. to ``False`` for each one. If the user referenced any nonexistent polls, a
  60. :class:`CommandError` is raised. The ``poll.opened`` attribute does not exist
  61. in the :doc:`tutorial</intro/tutorial01>` and was added to
  62. ``polls.models.Poll`` for this example.
  63. The same ``closepoll`` could be easily modified to delete a given poll instead
  64. of closing it by accepting additional command line options. These custom options
  65. must be added to :attr:`~BaseCommand.option_list` like this:
  66. .. code-block:: python
  67. from optparse import make_option
  68. class Command(BaseCommand):
  69. option_list = BaseCommand.option_list + (
  70. make_option('--delete',
  71. action='store_true',
  72. dest='delete',
  73. default=False,
  74. help='Delete poll instead of closing it'),
  75. )
  76. def handle(self, *args, **options):
  77. # ...
  78. if options['delete']:
  79. poll.delete()
  80. # ...
  81. The option (``delete`` in our example) is available in the options dict
  82. parameter of the handle method. See the :py:mod:`optparse` Python documentation
  83. for more about ``make_option`` usage.
  84. In addition to being able to add custom command line options, all
  85. :doc:`management commands</ref/django-admin>` can accept some
  86. default options such as :djadminopt:`--verbosity` and :djadminopt:`--traceback`.
  87. .. admonition:: Management commands and locales
  88. The :meth:`BaseCommand.execute` method sets the hardcoded ``en-us`` locale
  89. because the commands shipped with Django perform several tasks
  90. (for example, user-facing content rendering and database population) that
  91. require a system-neutral string language (for which we use ``en-us``).
  92. If your custom management command uses another locale, you should manually
  93. activate and deactivate it in your :meth:`~BaseCommand.handle` or
  94. :meth:`~NoArgsCommand.handle_noargs` method using the functions provided by
  95. the I18N support code:
  96. .. code-block:: python
  97. from django.core.management.base import BaseCommand, CommandError
  98. from django.utils import translation
  99. class Command(BaseCommand):
  100. ...
  101. self.can_import_settings = True
  102. def handle(self, *args, **options):
  103. # Activate a fixed locale, e.g. Russian
  104. translation.activate('ru')
  105. # Or you can activate the LANGUAGE_CODE
  106. # chosen in the settings:
  107. #
  108. #from django.conf import settings
  109. #translation.activate(settings.LANGUAGE_CODE)
  110. # Your command logic here
  111. # ...
  112. translation.deactivate()
  113. Take into account though, that system management commands typically have to
  114. be very careful about running in non-uniform locales, so:
  115. * Make sure the :setting:`USE_I18N` setting is always ``True`` when running
  116. the command (this is one good example of the potential problems stemming
  117. from a dynamic runtime environment that Django commands avoid offhand by
  118. always using a fixed locale).
  119. * Review the code of your command and the code it calls for behavioral
  120. differences when locales are changed and evaluate its impact on
  121. predictable behavior of your command.
  122. Command objects
  123. ===============
  124. .. class:: BaseCommand
  125. The base class from which all management commands ultimately derive.
  126. Use this class if you want access to all of the mechanisms which
  127. parse the command-line arguments and work out what code to call in
  128. response; if you don't need to change any of that behavior,
  129. consider using one of its :ref:`subclasses<ref-basecommand-subclasses>`.
  130. Subclassing the :class:`BaseCommand` class requires that you implement the
  131. :meth:`~BaseCommand.handle` method.
  132. Attributes
  133. ----------
  134. All attributes can be set in your derived class and can be used in
  135. :class:`BaseCommand`'s :ref:`subclasses<ref-basecommand-subclasses>`.
  136. .. attribute:: BaseCommand.args
  137. A string listing the arguments accepted by the command,
  138. suitable for use in help messages; e.g., a command which takes
  139. a list of application names might set this to '<appname
  140. appname ...>'.
  141. .. attribute:: BaseCommand.can_import_settings
  142. A boolean indicating whether the command needs to be able to
  143. import Django settings; if ``True``, ``execute()`` will verify
  144. that this is possible before proceeding. Default value is
  145. ``True``.
  146. .. attribute:: BaseCommand.help
  147. A short description of the command, which will be printed in the
  148. help message when the user runs the command
  149. ``python manage.py help <command>``.
  150. .. attribute:: BaseCommand.option_list
  151. This is the list of ``optparse`` options which will be fed
  152. into the command's ``OptionParser`` for parsing arguments.
  153. .. attribute:: BaseCommand.output_transaction
  154. A boolean indicating whether the command outputs SQL
  155. statements; if ``True``, the output will automatically be
  156. wrapped with ``BEGIN;`` and ``COMMIT;``. Default value is
  157. ``False``.
  158. .. attribute:: BaseCommand.requires_model_validation
  159. A boolean; if ``True``, validation of installed models will be
  160. performed prior to executing the command. Default value is
  161. ``True``. To validate an individual application's models
  162. rather than all applications' models, call
  163. :meth:`~BaseCommand.validate` from :meth:`~BaseCommand.handle`.
  164. Methods
  165. -------
  166. :class:`BaseCommand` has a few methods that can be overridden but only
  167. the :meth:`~BaseCommand.handle` method must be implemented.
  168. .. admonition:: Implementing a constructor in a subclass
  169. If you implement ``__init__`` in your subclass of :class:`BaseCommand`,
  170. you must call :class:`BaseCommand`'s ``__init__``.
  171. .. code-block:: python
  172. class Command(BaseCommand):
  173. def __init__(self, *args, **kwargs):
  174. super(Command, self).__init__(*args, **kwargs)
  175. # ...
  176. .. method:: BaseCommand.get_version()
  177. Return the Django version, which should be correct for all
  178. built-in Django commands. User-supplied commands can
  179. override this method to return their own version.
  180. .. method:: BaseCommand.execute(*args, **options)
  181. Try to execute this command, performing model validation if
  182. needed (as controlled by the attribute
  183. :attr:`requires_model_validation`). If the command raises a
  184. :class:`CommandError`, intercept it and print it sensibly to
  185. stderr.
  186. .. admonition:: Calling a management command in your code
  187. ``execute()`` should not be called directly from your code to execute a
  188. command. Use :ref:`call_command <call-command>` instead.
  189. .. method:: BaseCommand.handle(*args, **options)
  190. The actual logic of the command. Subclasses must implement this method.
  191. .. _ref-basecommand-subclasses:
  192. BaseCommand subclasses
  193. ----------------------
  194. .. class:: AppCommand
  195. A management command which takes one or more installed application
  196. names as arguments, and does something with each of them.
  197. Rather than implementing :meth:`~BaseCommand.handle`, subclasses must implement
  198. :meth:`~AppCommand.handle_app`, which will be called once for each application.
  199. .. method:: AppCommand.handle_app(app, **options)
  200. Perform the command's actions for ``app``, which will be the
  201. Python module corresponding to an application name given on
  202. the command line.
  203. .. class:: LabelCommand
  204. A management command which takes one or more arbitrary arguments
  205. (labels) on the command line, and does something with each of
  206. them.
  207. Rather than implementing :meth:`~BaseCommand.handle`, subclasses must implement
  208. :meth:`~LabelCommand.handle_label`, which will be called once for each label.
  209. .. method:: LabelCommand.handle_label(label, **options)
  210. Perform the command's actions for ``label``, which will be the
  211. string as given on the command line.
  212. .. class:: NoArgsCommand
  213. A command which takes no arguments on the command line.
  214. Rather than implementing :meth:`~BaseCommand.handle`, subclasses must implement
  215. :meth:`~NoArgsCommand.handle_noargs`; :meth:`~BaseCommand.handle` itself is
  216. overridden to ensure no arguments are passed to the command.
  217. .. method:: NoArgsCommand.handle_noargs(**options)
  218. Perform this command's actions
  219. .. _ref-command-exceptions:
  220. Command exceptions
  221. ------------------
  222. .. class:: CommandError
  223. Exception class indicating a problem while executing a management
  224. command.
  225. If this exception is raised during the execution of a management
  226. command, it will be caught and turned into a nicely-printed error
  227. message to the appropriate output stream (i.e., stderr); as a
  228. result, raising this exception (with a sensible description of the
  229. error) is the preferred way to indicate that something has gone
  230. wrong in the execution of a command.