Debian Codegraph @

pecan/configuration.py

raw
1 import re
2 import inspect
3 import os
4 import sys
5 from importlib.machinery import SourceFileLoader
6
7
8 IDENTIFIER = re.compile(r'[a-z_](\w)*$', re.IGNORECASE)
9
10 DEFAULT = {
11 # Server Specific Configurations
12 'server': {
13 'port': '8080',
14 'host': '0.0.0.0'
15 },
16
17 # Pecan Application Configurations
18 'app': {
19 'root': None,
20 'modules': [],
21 'static_root': 'public',
22 'template_path': '',
23 'force_canonical': True
24 }
25 }
26
27
28 class ConfigDict(dict):
29 pass
30
31
32 class Config(object):
33 '''
34 Base class for Pecan configurations.
35
36 Create a Pecan configuration object from a dictionary or a
37 filename.
38
39 :param conf_dict: A python dictionary to use for the configuration.
40 :param filename: A filename to use for the configuration.
41 '''
42
43 def __init__(self, conf_dict=None, filename=''):
44 self.__values__ = {}
45 self.__file__ = filename
46 conf_dict = conf_dict or {}
47 self.update(conf_dict)
48
49 def empty(self):
50 self.__values__ = {}
51
52 def update(self, conf_dict):
53 '''
54 Updates this configuration with a dictionary.
55
56 :param conf_dict: A python dictionary to update this configuration
57 with.
58 '''
59
60 if isinstance(conf_dict, dict):
61 iterator = iter(conf_dict.items())
62 else:
63 iterator = iter(conf_dict)
64
65 for k, v in iterator:
66 if not IDENTIFIER.match(k):
67 msg = ("'%s' is not a valid Python identifier,"
68 "consider using the '__force_dict__' key if requiring "
69 "a native dictionary")
70 raise ValueError(msg % k)
71
72 cur_val = self.__values__.get(k)
73
74 if isinstance(cur_val, Config):
75 cur_val.update(conf_dict[k])
76 else:
77 self[k] = conf_dict[k]
78
79 def get(self, attribute, default=None):
80 try:
81 return self[attribute]
82 except KeyError:
83 return default
84
85 def __dictify__(self, obj, prefix):
86 '''
87 Private helper method for to_dict.
88 '''
89 for k, v in obj.copy().items():
90 if prefix:
91 del obj[k]
92 k = "%s%s" % (prefix, k)
93 if isinstance(v, Config):
94 v = self.__dictify__(dict(v), prefix)
95 obj[k] = v
96 return obj
97
98 def to_dict(self, prefix=None):
99 '''
100 Converts recursively the Config object into a valid dictionary.
101
102 :param prefix: A string to optionally prefix all key elements in the
103 returned dictonary.
104 '''
105
106 conf_obj = dict(self)
107 return self.__dictify__(conf_obj, prefix)
108
109 def __getattr__(self, name):
110 try:
111 return self.__values__[name]
112 except KeyError:
113 msg = "'pecan.conf' object has no attribute '%s'" % name
114 raise AttributeError(msg)
115
116 def __setattr__(self, key, value):
117 if key not in ('__values__', '__file__'):
118 self.__setitem__(key, value)
119 return
120 super(Config, self).__setattr__(key, value)
121
122 def __getitem__(self, key):
123 return self.__values__[key]
124
125 def __setitem__(self, key, value):
126 if isinstance(value, dict) and not isinstance(value, ConfigDict):
127 if value.get('__force_dict__'):
128 del value['__force_dict__']
129 self.__values__[key] = ConfigDict(value)
130 else:
131 self.__values__[key] = Config(value, filename=self.__file__)
132 elif isinstance(value, str) and '%(confdir)s' in value:
133 confdir = os.path.dirname(self.__file__) or os.getcwd()
134 self.__values__[key] = value.replace('%(confdir)s', confdir)
135 else:
136 self.__values__[key] = value
137
138 def __iter__(self):
139 return iter(self.__values__.items())
140
141 def __dir__(self):
142 """
143 When using dir() returns a list of the values in the config. Note:
144 This function only works in Python2.6 or later.
145 """
146 return list(self.__values__.keys())
147
148 def __repr__(self):
149 return 'Config(%s)' % str(self.__values__)
150
151
152 def conf_from_file(filepath):
153 '''
154 Creates a configuration dictionary from a file.
155
156 :param filepath: The path to the file.
157 '''
158
159 abspath = os.path.abspath(os.path.expanduser(filepath))
160 conf_dict = {}
161 if not os.path.isfile(abspath):
162 raise RuntimeError('`%s` is not a file.' % abspath)
163
164 # First, make sure the code will actually compile (and has no SyntaxErrors)
165 with open(abspath, 'rb') as f:
166 compiled = compile(f.read(), abspath, 'exec')
167
168 # Next, attempt to actually import the file as a module.
169 # This provides more verbose import-related error reporting than exec()
170 absname, _ = os.path.splitext(abspath)
171 basepath, module_name = absname.rsplit(os.sep, 1)
172 SourceFileLoader(module_name, abspath).load_module(module_name)
173
174 # If we were able to import as a module, actually exec the compiled code
175 exec(compiled, globals(), conf_dict)
176 conf_dict['__file__'] = abspath
177
178 return conf_from_dict(conf_dict)
179
180
181 def get_conf_path_from_env():
182 '''
183 If the ``PECAN_CONFIG`` environment variable exists and it points to
184 a valid path it will return that, otherwise it will raise
185 a ``RuntimeError``.
186 '''
187 config_path = os.environ.get('PECAN_CONFIG')
188 if not config_path:
189 error = "PECAN_CONFIG is not set and " \
190 "no config file was passed as an argument."
191 elif not os.path.isfile(config_path):
192 error = "PECAN_CONFIG was set to an invalid path: %s" % config_path
193 else:
194 return config_path
195
196 raise RuntimeError(error)
197
198
199 def conf_from_dict(conf_dict):
200 '''
201 Creates a configuration dictionary from a dictionary.
202
203 :param conf_dict: The configuration dictionary.
204 '''
205 conf = Config(filename=conf_dict.get('__file__', ''))
206
207 for k, v in iter(conf_dict.items()):
208 if k.startswith('__'):
209 continue
210 elif inspect.ismodule(v):
211 continue
212
213 conf[k] = v
214 return conf
215
216
217 def initconf():
218 '''
219 Initializes the default configuration and exposes it at
220 ``pecan.configuration.conf``, which is also exposed at ``pecan.conf``.
221 '''
222 return conf_from_dict(DEFAULT)
223
224
225 def set_config(config, overwrite=False):
226 '''
227 Updates the global configuration.
228
229 :param config: Can be a dictionary containing configuration, or a string
230 which represents a (relative) configuration filename.
231 '''
232
233 if config is None:
234 config = get_conf_path_from_env()
235
236 # must be after the fallback other a bad fallback will incorrectly clear
237 if overwrite is True:
238 _runtime_conf.empty()
239
240 if isinstance(config, str):
241 config = conf_from_file(config)
242 _runtime_conf.update(config)
243 if config.__file__:
244 _runtime_conf.__file__ = config.__file__
245 elif isinstance(config, dict):
246 _runtime_conf.update(conf_from_dict(config))
247 else:
248 raise TypeError('%s is neither a dictionary or a string.' % config)
249
250
251 _runtime_conf = initconf()