[mod_python] Exceptions in the mod_python handler?

Graham Dumpleton graham.dumpleton at gmail.com
Wed Jan 9 19:27:11 EST 2008


On 07/01/2008, 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. 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?

Yes it is bad design.

At least do something like:

  dbcon = None
  def getdbcon():
    if not dbcon:
        dbcon = pyscopg2.connect("blah")
    return dbcon

  def index(req, dbcon=dbcon):
       curs = getdbcon().cursor()

That way the exception is raised from within your handler.

Note that this code is not thread safe, so you should make it so if
using worker MPM with Apache. This would require at the minimum locks
around the check to see if the dbcon has already been created or not.

You may also have to deal with issues of module reloading as well, so
make sure you read documentation for import_module() in:

  http://www.modpython.org/live/current/doc-html/pyapi-apmeth.html

Especially look for section on __mp_clone__() hook function.

If you aren't using mod_python 3.3.1 then upgrade.

Depending on the database being used, it is easier and not much less
efficient to simply create the database connection for very request
that requires it. That will save you a lot of trouble.

Graham


More information about the Mod_python mailing list