Skip to content

Commit 0f54b6d

Browse files
committed
add configurations
1 parent eef2a4c commit 0f54b6d

3 files changed

Lines changed: 91 additions & 0 deletions

File tree

www/config.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
4+
'''
5+
Configuration
6+
'''
7+
8+
__author__ = 'Michael Liao'
9+
10+
import config_default
11+
12+
class Dict(dict):
13+
'''
14+
Simple dict but support access as x.y style.
15+
'''
16+
def __init__(self, names=(), values=(), **kw):
17+
super(Dict, self).__init__(**kw)
18+
for k, v in zip(names, values):
19+
self[k] = v
20+
21+
def __getattr__(self, key):
22+
try:
23+
return self[key]
24+
except KeyError:
25+
raise AttributeError(r"'Dict' object has no attribute '%s'" % key)
26+
27+
def __setattr__(self, key, value):
28+
self[key] = value
29+
30+
def merge(defaults, override):
31+
r = {}
32+
for k, v in defaults.iteritems():
33+
if k in override:
34+
if isinstance(v, dict):
35+
r[k] = merge(v, override[k])
36+
else:
37+
r[k] = override[k]
38+
else:
39+
r[k] = v
40+
return r
41+
42+
def toDict(d):
43+
D = Dict()
44+
for k, v in d.iteritems():
45+
D[k] = toDict(v) if isinstance(v, dict) else v
46+
return D
47+
48+
configs = config_default.configs
49+
50+
try:
51+
import config_override
52+
configs = merge(configs, config_override.configs)
53+
except ImportError:
54+
pass
55+
56+
configs = toDict(configs)

www/config_default.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
4+
__author__ = 'Michael Liao'
5+
6+
'''
7+
Default configurations.
8+
'''
9+
10+
configs = {
11+
'db': {
12+
'host': '127.0.0.1',
13+
'port': 3306,
14+
'user': 'www-data',
15+
'password': 'www-data',
16+
'database': 'awesome'
17+
},
18+
'session': {
19+
'secret': 'AwEsOmE'
20+
}
21+
}

www/config_override.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
4+
'''
5+
Override configurations.
6+
'''
7+
8+
__author__ = 'Michael Liao'
9+
10+
configs = {
11+
'db': {
12+
'host': '127.0.0.1'
13+
}
14+
}

0 commit comments

Comments
 (0)