print_settings.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. # -*- coding: utf-8 -*-
  2. """
  3. print_settings
  4. ==============
  5. Django command similar to 'diffsettings' but shows all active Django settings.
  6. """
  7. import json
  8. from django.conf import settings
  9. from django.core.management.base import BaseCommand, CommandError
  10. from django_extensions.management.utils import signalcommand
  11. class Command(BaseCommand):
  12. help = "Print the active Django settings."
  13. def add_arguments(self, parser):
  14. super().add_arguments(parser)
  15. parser.add_argument(
  16. 'setting',
  17. nargs='*',
  18. help='Specifies setting to be printed.'
  19. )
  20. parser.add_argument(
  21. '--format',
  22. default='simple',
  23. dest='format',
  24. help='Specifies output format.'
  25. )
  26. parser.add_argument(
  27. '--indent',
  28. default=4,
  29. dest='indent',
  30. type=int,
  31. help='Specifies indent level for JSON and YAML'
  32. )
  33. @signalcommand
  34. def handle(self, *args, **options):
  35. a_dict = {}
  36. for attr in dir(settings):
  37. if self.include_attr(attr, options['setting']):
  38. value = getattr(settings, attr)
  39. a_dict[attr] = value
  40. for setting in args:
  41. if setting not in a_dict:
  42. raise CommandError('%s not found in settings.' % setting)
  43. output_format = options['format']
  44. indent = options['indent']
  45. if output_format == 'json':
  46. print(json.dumps(a_dict, indent=indent))
  47. elif output_format == 'yaml':
  48. import yaml # requires PyYAML
  49. print(yaml.dump(a_dict, indent=indent))
  50. elif output_format == 'pprint':
  51. from pprint import pprint
  52. pprint(a_dict)
  53. elif output_format == 'text':
  54. for key, value in a_dict.items():
  55. print("%s = %s" % (key, value))
  56. elif output_format == 'value':
  57. for value in a_dict.values():
  58. print(value)
  59. else:
  60. self.print_simple(a_dict)
  61. @staticmethod
  62. def include_attr(attr, settings):
  63. if attr.startswith('__'):
  64. return False
  65. elif settings == []:
  66. return True
  67. elif attr in settings:
  68. return True
  69. @staticmethod
  70. def print_simple(a_dict):
  71. for key, value in a_dict.items():
  72. print('%-40s = %r' % (key, value))