]> git.phdru.name Git - m_lib.git/blob - m_lib/flad/fladc.py
Replace <> with != for Py3 compatibility
[m_lib.git] / m_lib / flad / fladc.py
1 """
2    Flat ASCII Database to implement VERY simple config files.
3 """
4
5
6 import flad, fladm
7
8
9 error = "fladc.error" # Too many records
10
11
12 class Flad_Conf(dict):
13    """
14       FLAD config is just FLAD Database with exactly ONE record.
15       Flad_Conf objects are just UserDicts.
16    """
17    def __init__(self, must_keys = None, other_keys = None):
18       dict.__init__(self)
19
20       self.must_keys = must_keys
21       self.other_keys = other_keys
22
23
24    def __make_db(self):
25       if self.must_keys:
26          db = fladm.Flad_WithMustKeys(check_record, self.must_keys, self.other_keys)
27       else:
28          db = flad.Flad()
29
30       return db
31
32
33    def load_file(self, f):
34       db = self.__make_db()
35       db.load_file(f)
36
37       if len(db) != 1:
38          raise error, "incorrect number of records in config file `%s'; expected 1, got %d" % (str(f), len(db))
39
40       self.data = db[0]
41
42
43    def load_from_file(self, f):
44       db = self.__make_db()
45       db.load_from_file(f)
46
47       if len(db) != 1:
48          raise error, "incorrect number of records in config file `%s'; expected 1, got %d" % (str(f), len(db))
49
50       self.data = db[0]
51
52
53    def store_to_file(self, f):
54       db = self.__make_db()
55       db.append(self.data)
56       db.store_to_file(f)
57
58
59 def check_record(data, record): # Only allow append 1 record
60    return len(data) == 0
61
62
63 def load_file(f, must_keys = None, other_keys = None):
64    """
65       Create a database object and load it from file
66    """
67
68    db = Flad_Conf(must_keys, other_keys)
69    db.load_file(f)
70
71    return db
72
73
74 def load_from_file(f, must_keys = None, other_keys = None):
75    """
76       Create a database object and load it from file
77    """
78
79    db = Flad_Conf(must_keys, other_keys)
80    db.load_from_file(f)
81
82    return db