[mod_python] Raising Exceptions

John Keyes john.keyes at secantus.com
Fri Sep 29 06:09:53 EDT 2006


Hi guys,

I've included some test code (see below) for some weird
behaviour I've noticed.

I have dispatcher.py set up as a handler which dynamically
imports another handler (testhandler.py) and then calls
it's handler function.

The handler function in testhandler throws a user defined
exception (see __init__.py) which the dispatcher is
explicity set up to catch (see except MyError).

If I import testhandler using apache.import_module I
get the following output:

  test
  testhandler - b4 raise
  exception - MyError - jk

Yet if I use __import__ and getattr I get the following
output:

  test
  testhandler - b4 raise
  myerror

As you can see using import_module the incorrect except
block is executed, but the class name of the exception
is correct.

Can anyone explain to me why this is the case?

I've the code included inline but if you want to run the
code I've attached a zip file as well.

Apache     - 2.0.58
mod_python - 3.2.8
Python     - 2.4.3

Cheers,
-John K

== test.__init__.py ==
class MyError(Exception):
    def __init__(self, msg):
        self.msg = msg

    def __str__(self):
        return self.msg

== test.dispatcher.py ==
from mod_python import apache

from test import MyError

def handler(req):
    req.write("\ntest")

    try:
        #test_handler = apache.import_module('test.handlers.testhandler')
        test_handler = my_import('test.handlers.testhandler')
        val = test_handler.handler(req)
    except MyError, me:
        req.write("\nmyerror")
    except Exception, e:
        req.write("\nexception - %s - %s" % (e.__class__.__name__, e))

    return apache.OK

def my_import(name):
    mod = __import__(name)
    components = name.split('.')
    for comp in components[1:]:
        mod = getattr(mod, comp)
    return mod

== test.handlers.testhandler.py ==
from mod_python import apache

from test import MyError

def handler(req):
    req.write("\ntesthandler - b4 raise")

    raise MyError('jk')

    req.write("\ntesthandler - af raise")
    return apache.OK
-------------- next part --------------
A non-text attachment was scrubbed...
Name: import_test.zip
Type: application/zip
Size: 1113 bytes
Desc: not available
Url : http://mm_cfg_has_not_been_edited_to_set_host_domains/pipermail/mod_python/attachments/20060929/3bba7e00/import_test.zip


More information about the Mod_python mailing list