Updated mod_python Mako Handler

I have been using the mod_python handler to parse Mako templates for about a month now in a personal project. As I have done more and more development on my project, I have naturally encountered shortcomings and errors in my handler.

The first thing I encountered when using the handler was the incorrect status being returned after a template was parsed. Initially, I was not aware of the 500 status attached to all of the responses because the content came through correctly. Once I started to implement some AJAX features, everything came crashing down. While content was indeed returned, the ajax request looked at the status in the response header first, and started erring out all of my AJAX calls. I tracked this down to how I was previously setting the status so that it could be updated inside of the template:

req.status = apache.OK
return req.status

After some digging, I discovered that the reason for the 500 status was that I was attempting to set the status of the request. Instead of attempting to use the request status, I needed to make a temporary place-holder:

req.mako_status = apache.OK
return req.mako_status

After that fix, it was smooth sailing until I started integrating SQLAlchemy into my application. The moment I imported SQLAlchemy into my template file, mod_python started throwing error pages concerning the directory to cache eggs into. Because I had already been testing my ORM objects through the command line, this came as a surprise. The quick fix was to create a directory for it, and add it to the environment from within the handler. Once that was done, everything imported cleanly.

Now that I had my ORM objects imported, it was time to use them. As i was implementing a form-handling routine, I ran into another issue. When I passed in the raw value from the util.FieldStorage object provided by mod_python, I started receiving ProgrammingError exceptions from SQLAlchemy indicating that it was unable to adapt the select statements. After some digging, I found one little reference pointing back to the behavior of FieldStorage. I found the reason for the error here. FieldStorage was returning StringField objects instead of raw strings when I parsed the form inputs. When I placed those into the orm calls, it was unable to perform the needed type-matches. For the solution, I created a wrapper object for FieldStorage to implement some additional methods that did return string values.