custom-management-commands.txt 11 KB

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