Ticket #12821: __init__.py

File __init__.py, 2.5 KB (added by sorl, 15 years ago)
Line 
1import time
2import os
3import imp
4from django.conf import global_settings, LazySettings, ENVIRONMENT_VARIABLE
5from django.utils.importlib import import_module
6
7
8class Settings(object):
9 def __init__(self, settings_module):
10 self.set_from_module(global_settings)
11
12 # store the settings module in case someone later cares
13 self.SETTINGS_MODULE = settings_module
14
15 try:
16 project_settings = import_module(self.SETTINGS_MODULE)
17 except ImportError, e:
18 raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
19
20 # automatically set defaults from settings in app dir
21 for app in getattr(project_settings, 'INSTALLED_APPS', []):
22 try:
23 app_path = import_module(app).__path__
24 except AttributeError:
25 continue
26 try:
27 imp.find_module('settings', app_path)
28 except ImportError:
29 continue
30 app_settings = import_module('%s.settings' % app)
31 self.set_from_module(app_settings)
32
33 self.set_from_module(project_settings)
34
35 if hasattr(time, 'tzset'):
36 # Move the time zone info into os.environ. See ticket #2315 for why
37 # we don't do this unconditionally (breaks Windows).
38 os.environ['TZ'] = self.TIME_ZONE
39 time.tzset()
40
41 def set_from_module(self, mod):
42 for setting in dir(mod):
43 if setting == setting.upper():
44 setattr(self, setting, getattr(mod, setting))
45
46 def get_all_members(self):
47 return dir(self)
48
49
50class LazySettings(LazySettings):
51 def _setup(self):
52 """
53 Load the settings module pointed to by the environment variable. This
54 is used the first time we need any settings at all, if the user has not
55 previously configured the settings manually.
56 """
57 try:
58 settings_module = os.environ[ENVIRONMENT_VARIABLE]
59 if not settings_module: # If it's set but is an empty string.
60 raise KeyError
61 except KeyError:
62 # NOTE: This is arguably an EnvironmentError, but that causes
63 # problems with Python's interactive help.
64 raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE)
65
66 self._wrapped = Settings(settings_module)
67
68settings = LazySettings()
Back to Top