Source

django-swingcms / swingcms / modules / settingshandle.py

Full commit
#!/usr/bin/env python
# -*- coding: utf-8 -*-



__all__ = (
    'parse_settings',
    'store_settings'
)


def parse_settings(path):

    fd = open(path, 'rb')
    d = {}
    finish = False
    while not finish:
        setting = fd.readline()
        try:
            name, value = setting.split('=')
            d[name] = eval(value)
        except:
            pass
        if not setting:
            finish = True
    fd.close()
    return d


def store_settings(path, d):

    f = open(path, 'w')
    for name, value in d.items():
        if isinstance(value, basestring):
            f.writelines("%s='%s'\n" % (name, value))
        else:
            f.writelines('%s=%s\n' % (name, str(value)))
    f.close()


class SettingsHandler(dict):

    def __init__(self, path, *args, **kwargs):

        dict.__init__({}, *args, **kwargs)
        self.path = path
        self.parse()

    def __setitem__(self, name, value, store=True):

        dict.__setitem__(self, name, value)
        if store:
            self.store()

    def __getitem__(self, name):

        return dict.__getitem__(self, name)

    def parse(self):

        self.update(parse_settings(self.path))

    def store(self):

        store_settings(self.path, self)