[mod_python] returning errors from python handler and ErrorDocument

Jim Gallacher jpg at jgassociates.ca
Sat Nov 26 11:47:55 EST 2005

Nic Ferrier wrote:
> I've got a python handler that does this:
>    # something.py
>    def handler(http):
>       http.status = apache.UNAUTHORIZED
>       return apache.OK
> And in the apache config I've got something like:
>    <Location /something>
>    SetHandler python-program
>    PythonHandler something
>    </Location>
>    ErrorDocument 401 /somepage.html
> But the error document is not being served for requests to my
> handler. I think it should because I'm returning 401.
> Can someone enlighten me? Does the request processing just not work
> like that?

You would think that just setting the status would suffice but this does 
not seem to be the way it works. Without actually checking I imagine 
that the client will still see the req.status you set, plus whatever 
content your handler dishes out, but you have not told apache that you 
want to interupt processing have sling some different content. You do 
this by raising an exception.

from mod_python import apache

def handler(req):
     if unknown_user(req):
         raise apache.SERVER_RETURN, apache.HTTP_UNAUTHORIZED

     if  user_is_naughty(req):
         raise apache.SERVER_RETURN, apache.HTTP_FORBIDDEN

     if user_is_asking_for_something_silly(req):
         raise apache.SERVER_RETURN, apache.HTTP_NOT_FOUND

     req.write("It's all good")
     return apache.OK


More information about the Mod_python mailing list