PageRenderTime 37ms CodeModel.GetById 30ms RepoModel.GetById 1ms app.codeStats 0ms

/site/newsite/django_1_0/django/conf/__init__.py

https://github.com/joaoalf/geraldo
Python | 151 lines | 97 code | 17 blank | 37 comment | 14 complexity | e949b92e7bb3b210c629d59c96503676 MD5 | raw file
  1. """
  2. Settings and configuration for Django.
  3. Values will be read from the module specified by the DJANGO_SETTINGS_MODULE environment
  4. variable, and then from django.conf.global_settings; see the global settings file for
  5. a list of all possible variables.
  6. """
  7. import os
  8. import time # Needed for Windows
  9. from django.conf import global_settings
  10. ENVIRONMENT_VARIABLE = "DJANGO_SETTINGS_MODULE"
  11. class LazySettings(object):
  12. """
  13. A lazy proxy for either global Django settings or a custom settings object.
  14. The user can manually configure settings prior to using them. Otherwise,
  15. Django uses the settings module pointed to by DJANGO_SETTINGS_MODULE.
  16. """
  17. def __init__(self):
  18. # _target must be either None or something that supports attribute
  19. # access (getattr, hasattr, etc).
  20. self._target = None
  21. def __getattr__(self, name):
  22. if self._target is None:
  23. self._import_settings()
  24. if name == '__members__':
  25. # Used to implement dir(obj), for example.
  26. return self._target.get_all_members()
  27. return getattr(self._target, name)
  28. def __setattr__(self, name, value):
  29. if name == '_target':
  30. # Assign directly to self.__dict__, because otherwise we'd call
  31. # __setattr__(), which would be an infinite loop.
  32. self.__dict__['_target'] = value
  33. else:
  34. if self._target is None:
  35. self._import_settings()
  36. setattr(self._target, name, value)
  37. def _import_settings(self):
  38. """
  39. Load the settings module pointed to by the environment variable. This
  40. is used the first time we need any settings at all, if the user has not
  41. previously configured the settings manually.
  42. """
  43. try:
  44. settings_module = os.environ[ENVIRONMENT_VARIABLE]
  45. if not settings_module: # If it's set but is an empty string.
  46. raise KeyError
  47. except KeyError:
  48. # NOTE: This is arguably an EnvironmentError, but that causes
  49. # problems with Python's interactive help.
  50. raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE)
  51. self._target = Settings(settings_module)
  52. def configure(self, default_settings=global_settings, **options):
  53. """
  54. Called to manually configure the settings. The 'default_settings'
  55. parameter sets where to retrieve any unspecified values from (its
  56. argument must support attribute access (__getattr__)).
  57. """
  58. if self._target != None:
  59. raise RuntimeError, 'Settings already configured.'
  60. holder = UserSettingsHolder(default_settings)
  61. for name, value in options.items():
  62. setattr(holder, name, value)
  63. self._target = holder
  64. def configured(self):
  65. """
  66. Returns True if the settings have already been configured.
  67. """
  68. return bool(self._target)
  69. configured = property(configured)
  70. class Settings(object):
  71. def __init__(self, settings_module):
  72. # update this dict from global settings (but only for ALL_CAPS settings)
  73. for setting in dir(global_settings):
  74. if setting == setting.upper():
  75. setattr(self, setting, getattr(global_settings, setting))
  76. # store the settings module in case someone later cares
  77. self.SETTINGS_MODULE = settings_module
  78. try:
  79. mod = __import__(self.SETTINGS_MODULE, {}, {}, [''])
  80. except ImportError, e:
  81. raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
  82. # Settings that should be converted into tuples if they're mistakenly entered
  83. # as strings.
  84. tuple_settings = ("INSTALLED_APPS", "TEMPLATE_DIRS")
  85. for setting in dir(mod):
  86. if setting == setting.upper():
  87. setting_value = getattr(mod, setting)
  88. if setting in tuple_settings and type(setting_value) == str:
  89. setting_value = (setting_value,) # In case the user forgot the comma.
  90. setattr(self, setting, setting_value)
  91. # Expand entries in INSTALLED_APPS like "django.contrib.*" to a list
  92. # of all those apps.
  93. new_installed_apps = []
  94. for app in self.INSTALLED_APPS:
  95. if app.endswith('.*'):
  96. appdir = os.path.dirname(__import__(app[:-2], {}, {}, ['']).__file__)
  97. for d in os.listdir(appdir):
  98. if d.isalpha() and os.path.isdir(os.path.join(appdir, d)):
  99. new_installed_apps.append('%s.%s' % (app[:-2], d))
  100. else:
  101. new_installed_apps.append(app)
  102. self.INSTALLED_APPS = new_installed_apps
  103. if hasattr(time, 'tzset'):
  104. # Move the time zone info into os.environ. See ticket #2315 for why
  105. # we don't do this unconditionally (breaks Windows).
  106. os.environ['TZ'] = self.TIME_ZONE
  107. time.tzset()
  108. def get_all_members(self):
  109. return dir(self)
  110. class UserSettingsHolder(object):
  111. """
  112. Holder for user configured settings.
  113. """
  114. # SETTINGS_MODULE doesn't make much sense in the manually configured
  115. # (standalone) case.
  116. SETTINGS_MODULE = None
  117. def __init__(self, default_settings):
  118. """
  119. Requests for configuration variables not in this class are satisfied
  120. from the module specified in default_settings (if possible).
  121. """
  122. self.default_settings = default_settings
  123. def __getattr__(self, name):
  124. return getattr(self.default_settings, name)
  125. def get_all_members(self):
  126. return dir(self) + dir(self.default_settings)
  127. settings = LazySettings()