mod_python exception catching, other repetitious per-page actions

Jeff Epler jepler at unpythonic.net
Fri Mar 26 12:43:22 EST 2004


You could use a wrapper for each function, which at least keeps you
from needing the which_page argument..

    def page_wrapper(callable):
        def _wrapper(apache_request, *args):
            try:
                _connect_to_database()
                _do_user_specific_stuff(apache_request)
                return callable(*args)
            except Exception, err:
                return _TypesetErrorPage(err)
        return _wrapper

    def mainpage(apache_request, some_cgi_arg):
        # specific code ehre
    mainpage = page_wrapper(mainpage)
page_wrapper() could do extra magic with exec if you want it to have the
same signature as callable.. something like
    def page_wrapper(callable):
        d = {}
        name = callable.__name__
        argspec = getargspecstr(callable) # based on inspect.getargspec()
        callspec = ... # argspec with default values removed
        exec """def %s(%s): ... return callable(%s) ...""" \
            % (name, argspec, callspec) in d
        return d[name]
... barf, eh?

Jeff
PS one of the currently discussed PEPs may let you write
    def mainpage(apache_request, some_cgi_arg)[page_wrapper]: ...
instead of writing mainpage = page_wrapper(mainpage) after the function
body.




More information about the Python-list mailing list