Thursday, October 2, 2008

python and sweet cherrypy

I've been doing a lot of python sever-side programming lately, and I really like it. One diamond in the rough I've found is Cherrypy (http://www.cherrypy.com). Cherrypy is a very lightweight and pythonic web framework that does the bare-minimum needed to get you up and running with a model/view controller framework. After that its all up to you and it pretty much stays out of your way.

At its basic cherrypy is really just an application. They do include an http server that runs pretty well, and you can also run your app as a mod_wsgi or mod_python app.

Lets write hello world:

import cherrypy

class HelloWorld(object):
def index(self):
return "Hello World!"
index.exposed = True

cherrypy.quickstart(HelloWorld())

running this piece of code you see:

[02/Oct/2008:06:55:40] ENGINE Listening for SIGHUP.
[02/Oct/2008:06:55:40] ENGINE Listening for SIGTERM.
[02/Oct/2008:06:55:40] ENGINE Listening for SIGUSR1.
[02/Oct/2008:06:55:40] ENGINE Bus STARTING
CherryPy Checker:
The Application mounted at '' has an empty config.

[02/Oct/2008:06:55:40] ENGINE Started monitor thread '_TimeoutMonitor'.
[02/Oct/2008:06:55:40] ENGINE Started monitor thread 'Autoreloader'.
[02/Oct/2008:06:55:41] ENGINE Serving on 127.0.0.1:8080
[02/Oct/2008:06:55:41] ENGINE Bus STARTED

and going to http://127.0.0.1:8080/ you see "hello world".

Thats pretty much it.




I know I know, a lot of you are saying "Wait, why would I use this over something like JEE and rails that does all this majic for me?" There is no shortage of "out of the box" web frameworks that promise a "build your app in hours" magic


I've been using web frameworks going on 9 years, everything from JEE (Jboss), Ruby on Rails, and even Django. And they are all great. The probem is they are opinionated. To try and remove responsibilities from the developer they make decisions for you, for example:

  1. How they create and commit your db session between requests
  2. How many db sessions you can have.
  3. View rendering technologies
  4. which ORM to use
The list goes on and on. And if you are using one of these frameworks you are enjoing all these "freebies" if you agree to follow the opinion and rules set by the framework. However, the moment you have to go against one of these "pre-decisions" you can find yourself wrestling with the framework. Just try to extend RoR to have multiple db sessions. Or JBoss to use a "share nothing" architecture. I usually find these issues come out when addressing scaling issues specific to your user behavior.

With cherrypy's "minimal" architecture you are free to pretty much do what you want, but you have to do it. You decide how db sessions are opened and closed before and after requests, or how your controllers are stuctured. Its all up to you. And the interesting thing is when you start doing many of the "freebies" your self, you find you you weren't getting as much for free as you thought.

No comments: