PageRenderTime 62ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 0ms

/docs/howto/custom-management-commands.txt

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