Skip to content
Create a gist now

Instantly share code, notes, and snippets.

@zeha /config.py
Last active Dec 17, 2015

__all__ = ['Config']
import json, sys
class _Config():
def __init__(self):
self.filename = 'PROJECT.cfg'
self.load()
self.upgrade()
def load(self):
raw = ''
try:
f = open(self.filename, 'rt')
raw = f.read().split("\n")[1:]
f.close()
except Exception, e:
raw = ['{}']
try:
raw = "\n".join(raw)
self._c = json.loads(raw)
except Exception as e:
print "Error reading configuration:", repr(e)
raise
def upgrade(self):
self._upgrade(u'database', {u'connectstring': u'sqlite:///PROJECT.db'})
def _upgrade(self, toplevel, defaults):
if not toplevel in self._c:
self._c[toplevel] = {}
defaults.update(self._c[toplevel])
self._c[toplevel] = defaults
def save(self):
f = open(self.filename, 'wt')
f.write(" -*- mode: javascript -*- PROJECT config\n")
f.write(self.dump())
f.close()
def __getitem__(self, name):
v = self._c
for k in name.split('.'):
v = v[k]
return v
def dump(self):
return json.dumps(self._c, indent=2)
Config = _Config()
if __name__ == "__main__":
print "Configuration filename:", Config.filename
Config.save()
print Config.dump()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.