[mod_python] Exceptions in the mod_python handler?

Bart scarfboy at gmail.com
Mon Jan 7 13:37:23 EST 2008

On Jan 7, 2008 5:50 AM, Webb Sprague <webb.sprague at gmail.com> wrote:
> Hi all,
> I have a mod_python handler, called "lc.py", which has a bunch of
> functions -- mapped to pages --  called things "index",
> "process_request", etc.  Before defining those functions, I connect to
> the database with psycopg2 and pass that connection handle to each
> function/ page.
> <Directory /var/www/localhost/htdocs/lcfit>
>     SetHandler mod_python
>     PythonHandler mod_python.publisher
>     PythonDebug On
> </Directory>
> # This is lc.py in the lcfit directory
> dbcon = pyscopg2.connect("blah")
> def index(req, dbcon=dbcon):
>       curs = dbcon.cursor()
>       # etc
> This works fine usually.  However,  when the connection fails I don't
> know how to get apache to send some text to the user saying "call the
> admin and tell him to restart postgres."  At the moment I get a nice
> stack trace that I know how to read, but I would like to catch the
> exception, print something less intimidating, and quit processing the
> handler.

The stack trace comes from PythonDebug being On, as you probably know.
You can turn it off and raise an error that causes apache to generate its
generic error page (for the HTTP code), but this is probably no more
Since you'll probably want something app-specific, you'll probably want to
catch the error inside python and generate your own error page.

Exactly what and how depends on your wishes. I have an app in which
I should really hide the stack trace muck, but it's relatively rare as I
catch most errors inside handler code anyway, so I can probably get away
with a generic error handler for the few I forgot.
I'm thinking of doing so via a decorator, which is my pet method
of non-redundantly adding handler-wide things to multiple handlers.

> If I can somehow mark it so that apache knows to reload lc.py
> and attempt to reconnect the database the next time (hopefully after
> postgres is restarted), that would be especially great (touching the
> file?).
> Is this a bad design?  I am probably misunderstanding the order in
> which things are called (handlers, functions, modules, etc...), but I
> don't want each page to connect() and close() on each call, and I
> don't know where else to put the connection code except in the main
> handler.

Leaving connections open between page loads is technically possible,
but opens a world of worry and bordercases.
As I recall, psycopg does connection pooling anyway, so I'd suggest
reading up on how to use it.


More information about the Mod_python mailing list