How decoupled are the Python frameworks?

Martin Sand Christensen msc at es.aau.dk
Tue Dec 8 05:11:52 EST 2009


J Kenneth King <james at agentultra.com> writes:
> [...] (though it sounds like cherrypy would be very good at separating
> dispatching from application code).

True. In CherryPy, each page is represented by one method (the 'default'
method is an exception, but that's not for this discussion). This method
is expected to return a string representing the page/resource that the
user requested. At this simple level, CherryPy can be considered more or
less just a HTTP server and dispatcher.

However, we all know that this isn't where it ends. When we want to
handle cookies, we need framework-specific code. When we want to return
something other than HTML, we need framework-specific code. The list
goes on.

However, with a reasonable coding style, it can be quite practical to
separate strict application code from the framework-specific code. Here
the one-method,-one-page principle is a great help. For instance, we
quite often use decorators for such things as authentication and role
checking, which is both very practical and technically elegant. For
instance, if a user must have a CAS single sign-on identity AND, say,
the administrator role, we'd do as follows:

@cas
@role('administrator')
def protectedpage(self, ...):
    # stuff

If the user isn't currently signed in to our CAS, he'll be redirected to
the sign-in page and, after signing in, is returned to the page he
originally requested. The role decorator checks his privileges (based on
his CAS credentials) and either allows or denies him access. This adds
up to a LOT of framework-specific code that's been very easily factored
out. The CAS and role modules behind the decorators are, in turn,
generic frameworks that we've merely specialised for CherryPy. At some
point we'll get around to releasing some code. :-)

As a slight aside, allow me to recommend Meld3 as a good templating
library. It's basically ElementTree with a lot of practical templating
stuff on top, so it's not a mini-language unto itself, and you don't
embed your code in the page.

-- 
Martin Sand Christensen
IT Services, Dept. of Electronic Systems



More information about the Python-list mailing list