base.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. """
  2. Base classes for writing management commands (named commands which can
  3. be executed through ``django-admin.py`` or ``manage.py``).
  4. """
  5. import os
  6. import sys
  7. from io import BytesIO
  8. from optparse import make_option, OptionParser
  9. import traceback
  10. import django
  11. from django.core.exceptions import ImproperlyConfigured
  12. from django.core.management.color import color_style
  13. from django.utils.encoding import smart_str
  14. class CommandError(Exception):
  15. """
  16. Exception class indicating a problem while executing a management
  17. command.
  18. If this exception is raised during the execution of a management
  19. command, it will be caught and turned into a nicely-printed error
  20. message to the appropriate output stream (i.e., stderr); as a
  21. result, raising this exception (with a sensible description of the
  22. error) is the preferred way to indicate that something has gone
  23. wrong in the execution of a command.
  24. """
  25. pass
  26. def handle_default_options(options):
  27. """
  28. Include any default options that all commands should accept here
  29. so that ManagementUtility can handle them before searching for
  30. user commands.
  31. """
  32. if options.settings:
  33. os.environ['DJANGO_SETTINGS_MODULE'] = options.settings
  34. if options.pythonpath:
  35. sys.path.insert(0, options.pythonpath)
  36. class BaseCommand(object):
  37. """
  38. The base class from which all management commands ultimately
  39. derive.
  40. Use this class if you want access to all of the mechanisms which
  41. parse the command-line arguments and work out what code to call in
  42. response; if you don't need to change any of that behavior,
  43. consider using one of the subclasses defined in this file.
  44. If you are interested in overriding/customizing various aspects of
  45. the command-parsing and -execution behavior, the normal flow works
  46. as follows:
  47. 1. ``django-admin.py`` or ``manage.py`` loads the command class
  48. and calls its ``run_from_argv()`` method.
  49. 2. The ``run_from_argv()`` method calls ``create_parser()`` to get
  50. an ``OptionParser`` for the arguments, parses them, performs
  51. any environment changes requested by options like
  52. ``pythonpath``, and then calls the ``execute()`` method,
  53. passing the parsed arguments.
  54. 3. The ``execute()`` method attempts to carry out the command by
  55. calling the ``handle()`` method with the parsed arguments; any
  56. output produced by ``handle()`` will be printed to standard
  57. output and, if the command is intended to produce a block of
  58. SQL statements, will be wrapped in ``BEGIN`` and ``COMMIT``.
  59. 4. If ``handle()`` raised a ``CommandError``, ``execute()`` will
  60. instead print an error message to ``stderr``.
  61. Thus, the ``handle()`` method is typically the starting point for
  62. subclasses; many built-in commands and command types either place
  63. all of their logic in ``handle()``, or perform some additional
  64. parsing work in ``handle()`` and then delegate from it to more
  65. specialized methods as needed.
  66. Several attributes affect behavior at various steps along the way:
  67. ``args``
  68. A string listing the arguments accepted by the command,
  69. suitable for use in help messages; e.g., a command which takes
  70. a list of application names might set this to '<appname
  71. appname ...>'.
  72. ``can_import_settings``
  73. A boolean indicating whether the command needs to be able to
  74. import Django settings; if ``True``, ``execute()`` will verify
  75. that this is possible before proceeding. Default value is
  76. ``True``.
  77. ``help``
  78. A short description of the command, which will be printed in
  79. help messages.
  80. ``option_list``
  81. This is the list of ``optparse`` options which will be fed
  82. into the command's ``OptionParser`` for parsing arguments.
  83. ``output_transaction``
  84. A boolean indicating whether the command outputs SQL
  85. statements; if ``True``, the output will automatically be
  86. wrapped with ``BEGIN;`` and ``COMMIT;``. Default value is
  87. ``False``.
  88. ``requires_model_validation``
  89. A boolean; if ``True``, validation of installed models will be
  90. performed prior to executing the command. Default value is
  91. ``True``. To validate an individual application's models
  92. rather than all applications' models, call
  93. ``self.validate(app)`` from ``handle()``, where ``app`` is the
  94. application's Python module.
  95. """
  96. # Metadata about this command.
  97. option_list = (
  98. make_option('-v', '--verbosity', action='store', dest='verbosity', default='1',
  99. type='choice', choices=['0', '1', '2', '3'],
  100. help='Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output'),
  101. make_option('--settings',
  102. help='The Python path to a settings module, e.g. "myproject.settings.main". If this isn\'t provided, the DJANGO_SETTINGS_MODULE environment variable will be used.'),
  103. make_option('--pythonpath',
  104. help='A directory to add to the Python path, e.g. "/home/djangoprojects/myproject".'),
  105. make_option('--traceback', action='store_true',
  106. help='Print traceback on exception'),
  107. )
  108. help = ''
  109. args = ''
  110. # Configuration shortcuts that alter various logic.
  111. can_import_settings = True
  112. requires_model_validation = True
  113. output_transaction = False # Whether to wrap the output in a "BEGIN; COMMIT;"
  114. def __init__(self):
  115. self.style = color_style()
  116. def get_version(self):
  117. """
  118. Return the Django version, which should be correct for all
  119. built-in Django commands. User-supplied commands should
  120. override this method.
  121. """
  122. return django.get_version()
  123. def usage(self, subcommand):
  124. """
  125. Return a brief description of how to use this command, by
  126. default from the attribute ``self.help``.
  127. """
  128. usage = '%%prog %s [options] %s' % (subcommand, self.args)
  129. if self.help:
  130. return '%s\n\n%s' % (usage, self.help)
  131. else:
  132. return usage
  133. def create_parser(self, prog_name, subcommand):
  134. """
  135. Create and return the ``OptionParser`` which will be used to
  136. parse the arguments to this command.
  137. """
  138. return OptionParser(prog=prog_name,
  139. usage=self.usage(subcommand),
  140. version=self.get_version(),
  141. option_list=self.option_list)
  142. def print_help(self, prog_name, subcommand):
  143. """
  144. Print the help message for this command, derived from
  145. ``self.usage()``.
  146. """
  147. parser = self.create_parser(prog_name, subcommand)
  148. parser.print_help()
  149. def run_from_argv(self, argv):
  150. """
  151. Set up any environment changes requested (e.g., Python path
  152. and Django settings), then run this command.
  153. """
  154. parser = self.create_parser(argv[0], argv[1])
  155. options, args = parser.parse_args(argv[2:])
  156. handle_default_options(options)
  157. self.execute(*args, **options.__dict__)
  158. def execute(self, *args, **options):
  159. """
  160. Try to execute this command, performing model validation if
  161. needed (as controlled by the attribute
  162. ``self.requires_model_validation``, except if force-skipped). If the
  163. command raises a ``CommandError``, intercept it and print it sensibly
  164. to stderr.
  165. """
  166. show_traceback = options.get('traceback', False)
  167. # Switch to English, because django-admin.py creates database content
  168. # like permissions, and those shouldn't contain any translations.
  169. # But only do this if we can assume we have a working settings file,
  170. # because django.utils.translation requires settings.
  171. saved_lang = None
  172. if self.can_import_settings:
  173. try:
  174. from django.utils import translation
  175. saved_lang = translation.get_language()
  176. translation.activate('en-us')
  177. except ImportError as e:
  178. # If settings should be available, but aren't,
  179. # raise the error and quit.
  180. if show_traceback:
  181. traceback.print_exc()
  182. else:
  183. sys.stderr.write(smart_str(self.style.ERROR('Error: %s\n' % e)))
  184. sys.exit(1)
  185. try:
  186. self.stdout = options.get('stdout', sys.stdout)
  187. self.stderr = options.get('stderr', sys.stderr)
  188. if self.requires_model_validation and not options.get('skip_validation'):
  189. self.validate()
  190. output = self.handle(*args, **options)
  191. if output:
  192. if self.output_transaction:
  193. # This needs to be imported here, because it relies on
  194. # settings.
  195. from django.db import connections, DEFAULT_DB_ALIAS
  196. connection = connections[options.get('database', DEFAULT_DB_ALIAS)]
  197. if connection.ops.start_transaction_sql():
  198. self.stdout.write(self.style.SQL_KEYWORD(connection.ops.start_transaction_sql()) + '\n')
  199. self.stdout.write(output)
  200. if self.output_transaction:
  201. self.stdout.write('\n' + self.style.SQL_KEYWORD("COMMIT;") + '\n')
  202. except CommandError as e:
  203. if show_traceback:
  204. traceback.print_exc()
  205. else:
  206. self.stderr.write(smart_str(self.style.ERROR('Error: %s\n' % e)))
  207. sys.exit(1)
  208. finally:
  209. if saved_lang is not None:
  210. translation.activate(saved_lang)
  211. def validate(self, app=None, display_num_errors=False):
  212. """
  213. Validates the given app, raising CommandError for any errors.
  214. If app is None, then this will validate all installed apps.
  215. """
  216. from django.core.management.validation import get_validation_errors
  217. s = BytesIO()
  218. num_errors = get_validation_errors(s, app)
  219. if num_errors:
  220. s.seek(0)
  221. error_text = s.read()
  222. raise CommandError("One or more models did not validate:\n%s" % error_text)
  223. if display_num_errors:
  224. self.stdout.write("%s error%s found\n" % (num_errors, num_errors != 1 and 's' or ''))
  225. def handle(self, *args, **options):
  226. """
  227. The actual logic of the command. Subclasses must implement
  228. this method.
  229. """
  230. raise NotImplementedError()
  231. class AppCommand(BaseCommand):
  232. """
  233. A management command which takes one or more installed application
  234. names as arguments, and does something with each of them.
  235. Rather than implementing ``handle()``, subclasses must implement
  236. ``handle_app()``, which will be called once for each application.
  237. """
  238. args = '<appname appname ...>'
  239. def handle(self, *app_labels, **options):
  240. from django.db import models
  241. if not app_labels:
  242. raise CommandError('Enter at least one appname.')
  243. try:
  244. app_list = [models.get_app(app_label) for app_label in app_labels]
  245. except (ImproperlyConfigured, ImportError) as e:
  246. raise CommandError("%s. Are you sure your INSTALLED_APPS setting is correct?" % e)
  247. output = []
  248. for app in app_list:
  249. app_output = self.handle_app(app, **options)
  250. if app_output:
  251. output.append(app_output)
  252. return '\n'.join(output)
  253. def handle_app(self, app, **options):
  254. """
  255. Perform the command's actions for ``app``, which will be the
  256. Python module corresponding to an application name given on
  257. the command line.
  258. """
  259. raise NotImplementedError()
  260. class LabelCommand(BaseCommand):
  261. """
  262. A management command which takes one or more arbitrary arguments
  263. (labels) on the command line, and does something with each of
  264. them.
  265. Rather than implementing ``handle()``, subclasses must implement
  266. ``handle_label()``, which will be called once for each label.
  267. If the arguments should be names of installed applications, use
  268. ``AppCommand`` instead.
  269. """
  270. args = '<label label ...>'
  271. label = 'label'
  272. def handle(self, *labels, **options):
  273. if not labels:
  274. raise CommandError('Enter at least one %s.' % self.label)
  275. output = []
  276. for label in labels:
  277. label_output = self.handle_label(label, **options)
  278. if label_output:
  279. output.append(label_output)
  280. return '\n'.join(output)
  281. def handle_label(self, label, **options):
  282. """
  283. Perform the command's actions for ``label``, which will be the
  284. string as given on the command line.
  285. """
  286. raise NotImplementedError()
  287. class NoArgsCommand(BaseCommand):
  288. """
  289. A command which takes no arguments on the command line.
  290. Rather than implementing ``handle()``, subclasses must implement
  291. ``handle_noargs()``; ``handle()`` itself is overridden to ensure
  292. no arguments are passed to the command.
  293. Attempting to pass arguments will raise ``CommandError``.
  294. """
  295. args = ''
  296. def handle(self, *args, **options):
  297. if args:
  298. raise CommandError("Command doesn't accept any arguments")
  299. return self.handle_noargs(**options)
  300. def handle_noargs(self, **options):
  301. """
  302. Perform this command's actions.
  303. """
  304. raise NotImplementedError()