2 Flat ASCII Database with "must" keys
4 Written by Broytman. Copyright (C) 1997-2005 PhiloSoft Design
8 from flad import Flad, def_keysep
11 class Flad_WithMustKeys(Flad):
13 Database with two lists of keys - keys that must be in every record,
14 and keys that allowed to be in some records.
17 def __init__(self, check_record_func = None, must_keys = None, other_keys = None):
18 Flad.__init__(self, check_record_func)
19 self.must_keys = must_keys # Save keys lists to store...
20 self.other_keys = other_keys #... desired sequence of keys
23 def store_to_file(self, f):
24 if type(f) == type(''): # If f is string - use it as file's name
25 outfile = open(f, 'w')
27 outfile = f # else assume it is opened file (fileobject) or
28 # "compatible" object (must has write() method)
30 flush_record = 0 # Do not close record on 1st loop
33 copy_rec = record.copy() # Make a copy to delete keys
36 outfile.write('\n') # Close record
38 flush_record = 1 # Set flag for all but 1st record
41 for key in self.must_keys:
42 outfile.write(key + def_keysep + copy_rec[key] + '\n')
46 for key in self.other_keys:
47 if copy_rec.has_key(key):
48 outfile.write(key + def_keysep + copy_rec[key] + '\n')
52 for key in copy_rec.keys():
53 outfile.write(key + def_keysep + copy_rec[key] + '\n')
56 if type(f) == type(''): # If f was open - close it
60 def check_record(data, record):
62 Check record for consistency and append it to list of records
64 must_keys = data.must_keys
65 other_keys = data.other_keys
68 copy_must = must_keys[:] # Make a copy
72 for key in record.keys(): # Check every key
73 if must_keys and (key in must_keys):
74 del copy_must[copy_must.index(key)] # Remove the key from copied list
75 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)):
76 raise KeyError, "field key \"" + key + "\" is not in list of allowed keys"
78 if copy_must: # If there is at least one key - it is an error:
79 # not all "must" keys are in record
80 raise KeyError, "not all \"must\" keys are in record; keys: " + str(copy_must)
85 def load_file(f, check_record_func = None, must_keys = None, other_keys = None):
87 Create a database object and load it from file
90 db = Flad_WithMustKeys(check_record_func, must_keys, other_keys)
96 def load_from_file(f, check_record_func = None, must_keys = None, other_keys = None):
98 Create a database object and load it from file
101 db = Flad_WithMustKeys(check_record_func, must_keys, other_keys)