Debian Codegraph @

pecan/configuration.py

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