[Web-SIG] Web Form Handling Techniques

Ian Bicking ianb at colorstudy.com
Thu Jan 22 15:29:53 EST 2004


Lucid Drake wrote:
> I pass this information to a function called, insertData which
> looks something like this:
> 
> def insertData(data):
> 
>     # test data for validity
>     if not data['name'].isalpha():
>        raise InvalidDataError(data['name'], "Name contains non-alpha
>        characters")
>     if not data['age'].isdigit():
>        raise InvalidDataError(data['age'], "Age contains non-digit
>        characters")
> 
>     sql = """
>     INSERT INTO people (name, age) VALUES ('%s', '%s')
>     """ % (data['name'], data['age'])
> 
>     executeSQL(sql)
> 
> I should first check to see if the data is valid, meaning that the
> name contains only alpha characters and the age only containing
> numeric characters.

Try something more like:

def insertData(data):
     errors = {}
     if not data['name'].isalpha():
         errors['name'] = 'Name contains non-alpha characters'
     ....
     if errors:
         raise InvalidDataError(data, errors)
     sql = ...

Then look at the errors dictionary.  If you were putting each validation 
(and exception) in a separate function, then you might loop over the 
fields and do a try:except InvalidDataError: and then accumulate the 
results into a dictionary in the same fashion.

   Ian



More information about the Web-SIG mailing list