check.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. from django.apps import apps
  2. from django.core import checks
  3. from django.core.checks.registry import registry
  4. from django.core.management.base import BaseCommand, CommandError
  5. class Command(BaseCommand):
  6. help = "Checks the entire Django project for potential problems."
  7. requires_system_checks = []
  8. def add_arguments(self, parser):
  9. parser.add_argument('args', metavar='app_label', nargs='*')
  10. parser.add_argument(
  11. '--tag', '-t', action='append', dest='tags',
  12. help='Run only checks labeled with given tag.',
  13. )
  14. parser.add_argument(
  15. '--list-tags', action='store_true',
  16. help='List available tags.',
  17. )
  18. parser.add_argument(
  19. '--deploy', action='store_true',
  20. help='Check deployment settings.',
  21. )
  22. parser.add_argument(
  23. '--fail-level',
  24. default='ERROR',
  25. choices=['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'],
  26. help=(
  27. 'Message level that will cause the command to exit with a '
  28. 'non-zero status. Default is ERROR.'
  29. ),
  30. )
  31. parser.add_argument(
  32. '--database', action='append', dest='databases',
  33. help='Run database related checks against these aliases.',
  34. )
  35. def handle(self, *app_labels, **options):
  36. include_deployment_checks = options['deploy']
  37. if options['list_tags']:
  38. self.stdout.write('\n'.join(sorted(registry.tags_available(include_deployment_checks))))
  39. return
  40. if app_labels:
  41. app_configs = [apps.get_app_config(app_label) for app_label in app_labels]
  42. else:
  43. app_configs = None
  44. tags = options['tags']
  45. if tags:
  46. try:
  47. invalid_tag = next(
  48. tag for tag in tags if not checks.tag_exists(tag, include_deployment_checks)
  49. )
  50. except StopIteration:
  51. # no invalid tags
  52. pass
  53. else:
  54. raise CommandError('There is no system check with the "%s" tag.' % invalid_tag)
  55. self.check(
  56. app_configs=app_configs,
  57. tags=tags,
  58. display_num_errors=True,
  59. include_deployment_checks=include_deployment_checks,
  60. fail_level=getattr(checks, options['fail_level']),
  61. databases=options['databases'],
  62. )