[mod_python] Validating input - Form Handler component

Scott Chapman scott_list at mischko.com
Thu Oct 5 16:53:53 EDT 2006

Here's a more robust version:

class FormDict(dict):
     '''This is a special dict that checks items as they are assigned.
     It would be useful for web form submissions, etc.
     At dict creation, errors are accumulated, if any, and sent back as a 
     def __init__(self,**dictparms):
         # If there are defaults, assign them first:
         # self.__setitem__(key, value)
         # if you need to bypass your own setitem checking:
         # super(FormDict, self).__setitem__(key, mvalue)

         # Set the valid keys here:
         self.__valid_keys = ('id',)

         errors = []
         for key in dictparms:
                 self.__setitem__(key, dictparms[key])
             except RuntimeError,e:
         if errors:
             raise RuntimeError(errors)

     def __setitem__(self, key, value):
         if not key in self.__valid_keys:
             raise RuntimeError, "Invalid Key: %s" % key
         # Put your own checks here.
         # If you don't create a check for a given valid key, anything will be 
         if key =='id':
                 mvalue = int(value)
                 raise RuntimeError, "Invalid ID: %s" % mvalue
             if mvalue <= 0:
                 raise RuntimeError, "Invalid ID: %s" % mvalue
             super(FormDict, self).__setitem__(key, mvalue)
         elif key == 'foo':
             super(FormDict, self).__setitem__(key, mvalue)
         elif key in self.__valid_keys:
             super(FormDict, self).__setitem__(key, mvalue)
             raise RuntimeError, "Invalid Key"

if __name__ == '__main__':
         md = FormDict(id=1,name='bill',address='123 any street')
     except RuntimeError, e:
         error_list = list(e[0])
         for error in error_list:
             print error
     md = FormDict(id=1)

More information about the Mod_python mailing list