2 Flat ASCII Database with "must" keys
6 from m_lib.flad.flad import Flad, def_keysep
9 class Flad_WithMustKeys(Flad):
11 Database with two lists of keys - keys that must be in every record,
12 and keys that allowed to be in some records.
15 def __init__(self, check_record_func = None, must_keys = None, other_keys = None):
16 Flad.__init__(self, check_record_func)
17 self.must_keys = must_keys # Save keys lists to store...
18 self.other_keys = other_keys #... desired sequence of keys
21 def store_to_file(self, f):
22 if type(f) == type(''): # If f is string - use it as file's name
23 outfile = open(f, 'w')
25 outfile = f # else assume it is opened file (fileobject) or
26 # "compatible" object (must has write() method)
28 flush_record = 0 # Do not close record on 1st loop
31 copy_rec = record.copy() # Make a copy to delete keys
34 outfile.write('\n') # Close record
36 flush_record = 1 # Set flag for all but 1st record
39 for key in self.must_keys:
40 outfile.write(key + def_keysep + copy_rec[key] + '\n')
44 for key in self.other_keys:
46 outfile.write(key + def_keysep + copy_rec[key] + '\n')
50 for key in list(copy_rec.keys()):
51 outfile.write(key + def_keysep + copy_rec[key] + '\n')
54 if type(f) == type(''): # If f was open - close it
58 def check_record(data, record):
60 Check record for consistency and append it to list of records
62 must_keys = data.must_keys
63 other_keys = data.other_keys
66 copy_must = must_keys[:] # Make a copy
70 for key in record.keys(): # Check every key
71 if must_keys and (key in must_keys):
72 del copy_must[copy_must.index(key)] # Remove the key from copied list
73 elif (must_keys and (key not in must_keys) and (other_keys and (key not in other_keys))) or (other_keys and (key not in other_keys)):
74 raise KeyError("field key \"" + key + "\" is not in list of allowed keys")
76 if copy_must: # If there is at least one key - it is an error:
77 # not all "must" keys are in record
78 raise KeyError("not all \"must\" keys are in record; keys: " + str(copy_must))
83 def load_file(f, check_record_func = None, must_keys = None, other_keys = None):
85 Create a database object and load it from file
88 db = Flad_WithMustKeys(check_record_func, must_keys, other_keys)
94 def load_from_file(f, check_record_func = None, must_keys = None, other_keys = None):
96 Create a database object and load it from file
99 db = Flad_WithMustKeys(check_record_func, must_keys, other_keys)