def validate(self, **kw): # validate_edit only comes into force for field-by-field-edit style page so maybe belongs in a # subclass self.filename, = kw.pop('filename_', ('?fn',)) self.calling_script, = kw.pop('calling_script_', ('?cs',)) self.line_ = list(map(int, kw.pop('line_', (-1, -1)))) if not Page.validate(self, **kw): return False self.ee = None # we must avoid trying to create an entity which already exists according to the source file. self.EntityClass.by_range(self.line_).detach() # we usually need the following so let's get it done now. with open(self.filename, 'r') as module_src: self.all_lines = module_src.readlines() # the following method of dermining whether we're here as a from validator # is a bit stange but works. self.submitting = os.environ.get("REQUEST_METHOD") == "POST" if self.submitting and self.EntityClass: # So the user has finished editing an item which was taken from a page containing a list of such items. # If we're happy with his edit we return to that list page, otherwsie we stay on this page and helphim sort it out. # self.form = cgi.FieldStorage() requested_action = self.form.getfirst('button_') if requested_action in ('Add', 'Modify'): try: # Retrieve the fields and values and use thses to create a new or replacement instance. answers = [(mfs.name, mfs.value) for mfs in self.form.list if not mfs.name.endswith('_')] self.new_instance = self.EntityClass(**dict(answers)) except EntityError as ee: # except Exception as ee: # except KeyError as ee: print(ee, file=sys.stderr) self.ee = ee #print("Location: " + self.href('/testing/test3.py', {'exc': (str(ee),)}, "#%s" % self.line_[0]) + "\n\n") #return None if self.ee is None: # incorporate the updated entry into the module: if requested_action != 'Cancel': with open(self.filename, 'w') as module_src: module_src.writelines(self.all_lines[:self.line_[requested_action=='Add']]) if requested_action != 'Delete': module_src.write(str(self.new_instance)) module_src.writelines(self.all_lines[self.line_[1]:]) print("Location: " + self.href(self.calling_script, {}, "#%s" % self.line_[0]) + "\n\n") return None else: return True else: item_string = ''.join(self.all_lines[slice(*self.line_)]) print(item_string, file=sys.stderr) #print("Location: " + self.href('/testing/test3.py', {'item_string_': (str('item_string'),)}, "#%s" % self.line_[0]) + "\n\n") # return None self.new_instance = self.evaluate(item_string) return True