Wednesday, October 7, 2009

Form Encode Errors

The FormEncode Python package has grown to be the standard for validating web requests in Python web applications. Rather than implement some custom code that ensures incoming request data is what is expected, FormEncode provides validation functionality that is common. Although the package name suggests that the validation may only occur on form data, this is not the case fortunately. The validation may be applied to any data. The data might not even come from the web, although, that is what its' intended use is.

Parameters of web controllers that make up the application are what the developers of these applications want to validate. This is how external clients are able to get data into the application. Through the parameters of the controllers. It is thus important to ensure that this data is acceptable to the application.

With FormEncode, schemas may be defined by a controller. These schemas are defined on a per controller basis and include the parameters used by the controller. By using this method of parameter validation, each parameter of the controller can be validated at the same time instead of trying to validate each parameter individually.

However, with schemas that have many parameters to validate, more than one parameter may be at fault for the validation failure. In this case, the exception raised by the validation failure has no useful meaning as a whole. What the client needs is an explanation for why each individual field failed. An example of how this can be done is shown below.
#Example; Better formencode error handling.
import formencode

#A simple validation schema.
class Schema(formencode.Schema):
name=formencode.validators.String(not_empty=True)

#Get meaningful data from the formencode exception.
def format_error(e):
return e.error_dict

#Main.
if __name__=="__main__":

#Attempt to validate.
try:
Schema().to_python({"name":""})
except formencode.Invalid, e:
#Display the better error data.
print format_error(e)