Commit 809d67473a691bf91e54dba555beba62d47441cc
1 parent
c10e71f4
Exists in
master
Structure the configuration.
Time for a short coffee break! /spend 68h (cumulated sprint so far)
Showing
1 changed file
with
40 additions
and
1 deletions
Show diff stats
flaskr/content.py
1 | +from collections import namedtuple | |
1 | 2 | from yaml import safe_load as yaml_safe_load |
2 | 3 | |
3 | 4 | with open('content.yml', 'r') as content_file: |
4 | - content = yaml_safe_load(content_file.read()) | |
5 | + content_dict = yaml_safe_load(content_file.read()) | |
6 | + | |
7 | + | |
8 | +class Struct(object): | |
9 | + def __new__(cls, data): | |
10 | + if isinstance(data, dict): | |
11 | + return namedtuple( | |
12 | + 'Struct', data.iterkeys() | |
13 | + )( | |
14 | + *(Struct(val) for val in data.values()) | |
15 | + ) | |
16 | + elif isinstance(data, (tuple, list, set, frozenset)): | |
17 | + return type(data)(Struct(_) for _ in data) | |
18 | + else: | |
19 | + return data | |
20 | + | |
21 | + | |
22 | +content = Struct(content_dict) | |
23 | + | |
24 | +# For Python3? | |
25 | +# def dict2obj(d): | |
26 | +# """ | |
27 | +# Convert a dict to an object | |
28 | +# | |
29 | +# >>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]} | |
30 | +# >>> obj = dict2obj(d) | |
31 | +# >>> obj.b.c | |
32 | +# 2 | |
33 | +# >>> obj.d | |
34 | +# ["hi", {'foo': "bar"}] | |
35 | +# """ | |
36 | +# try: | |
37 | +# d = dict(d) | |
38 | +# except (TypeError, ValueError): | |
39 | +# return d | |
40 | +# obj = Object() | |
41 | +# for k, v in d.iteritems(): | |
42 | +# obj.__dict__[k] = dict2obj(v) | |
43 | +# return obj | ... | ... |