Tuesday, December 2, 2008

Cherrypy + Routes with mod_wsgi

If you haven't played around with deploying your python apps using mod_wsgi, I highly recommend it. It is a very stable way to deploy your application that takes advantage of the good parts of the apache2 runtime.

Vanilla Cherrypy apps run great as wsgi applications. However, I did come across a problem when deploying a Cherrypy app with Routes. Running the application using the cherrypy server worked fine, but deploying it using apache2 + mod_wsgi always gave me the following on every request:

503 Service Unavailable

The CherryPy engine has stopped.

After some looking around the mod_wsgi project (which is well documented I must say) I found the answer here: http://code.google.com/p/modwsgi/wiki/IntegrationWithCherryPy

When running a Cherrypy app with the routes dispatcher you need to make sure you call:

cherrypy.engine.start(blocking=False)

After mounting your app. This sets the cherrypy engine state to running. After doing this everything worked great and I now have beautiful restful routes in my mod_wsgi app.

Friday, November 21, 2008

REST with cherrypy

I've been doing web services for a while. And while SOAP definitively has its place, if you control both sites of the web service REST can really make life easier. Cherrypy with Python Routes pretty much makes this trivial. Obviously everyone knows how to route gets, but what about the nasty post and put (REST talk for create and update). NO problem.


d = cherrypy.dispatch.RoutesDispatcher()

d.connect('create_something', '/something', controller=root.something_controller, action='create_something',conditions=dict(method=['POST']))

What this is saying is I want a to route all routes that match /something and are of the method "POST" to the controller root.something_controller and the method "create_something". Thats it. PUT is just as easy.

d.connect('create_something', '/something/:id', controller=root.something_controller, action='update_something',conditions=dict(method=['PUT']))

Same thing as above except the method update_something will get the param id.

Sunday, October 5, 2008

routes with Cherrypy

As I posted earlier, my new favorite web framework is cherrypy. I love its simplicity and the fact that I'm not wrestling with magic to do exactly what I want to do. One bug knock against cherry py is its routing mechansim. By default it uses an object reference routing, so take the following:


class HelloWorld()
def index(self):
return "

Welcome

"

def say_hello(self):
return "

Hello World!

"

class Root(object):

hello = HelloWorld()
app = cherrypy.tree.mount(Root(), config=conf)
cherrypy.quickstart(app)



Notice that our Root object creates a controller as a member var called hello. By default the way we would have a browser call the "say hello" method is by:

http://127.0.0.1:8080/hello/say_hello

This is fine and simple, but as we all know in the world of search engine optimization you have to put as much into your urls as you do your content. This is why things like swimlanes and routes in frameworks such as rails and Servlets are so important. Not to fear becase you can do this in cherrypy also.

Cherrypy pretty much allows you to drop in any request dispatching mechanism you want. Thats the whole point of cherrypy is it completly stays out of your way so you can build the exact webapp you want. If you want to use the python routes package, go a ahead. If you want to write you own, more power to you.

Here is a tutorial on using routes with cherrypy.

Quickly, just by adding the following lines to the code where I start my cherrypy app:
 d = cherrypy.dispatch.RoutesDispatcher()
d.connect('blog', 'helloworld/, controller=Root.hello, action="say_hello")

And I now get routes style power!

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.

Friday, April 25, 2008

closures and you

So I'm diving into dynamic programming with Groovy and I love it. I consider myself an expert Java & C++ programmer, but I'm definitely having to do some re-learning with dynamic languages. I think its like when you encounter someone who, for some reason or another, really doesn't grasp object oriented methodologies. Its a way of thinking and designing your software that you really just have to understand. I think programming in dynamic languages, while very different, follow the same learning process. And I'm definitely in it.

So lets start with closures, probably the most verbalized features of dynamic languages.


Obviously the most famous is iterating a list. Lets say I want to print out every element in a list... obviously I could do the following in straight java.

Vector list = new Vector();
// add stuff to the list
for ( Object x : list)
System.out.println(x);

In groovy I can do:

def list = ["one","two","three"]
list.each { println ${it}}

The idea is I actually pass the list a segment of "code" to execute on itself. But wait, it gets better.

Lets say I want to create a function that will do something n times... easy in Groovy:

def doSometing(number, Closure c) {
0.upto(number) {c}

}

// now you can call the method like this:
doSomething (4) { println "Say Hello" }

Pretty smooth huh? Obviously the possibilities are endless and, possibly dangerous. When passing a closure to an object, you basically give it permission do do whatever it wants

class Hello {
String name
String important = "DON'T CHANGE"

def Hello (name, Closure c) {
this.name = name

c()
}
}


I can then create a Hello object like this

def h = new Hello("Jonathan" ) { this.important = "BAD"}

And the Hello object's important field will be changed, even if I make it private. Makes it a little difficult to create well-formed and protected libraries.

Thursday, April 17, 2008

grails and the nulls that confuse me

Recently I've started doing a lot of my work in groovy. Being an old fart I love my java, but many of the young guys are pushing me to pick up the dynamic languages of the times. I'm not a fan of Ruby (mostly due to the community, you know who) and while I like Python it just doesn't fit for scalable enterprise systems.

Then I noticed groovy, and I love it. I have all the power of java with the syntactical candy of dynamic languages. And Grails is really awesome (especially the 1.x series). Its like Ruby on Rails, but made by people who really want to use it in production. I can write groovy code, and use hibernate, and run on top of a clustered Jetty with terracotta, how cool is that?

I do have to say, its the little things that get you. A good example is GORM and exception handling. In EJB3 or even straight hibernate, when I save an object that doesn't validate I'll get a java.lang.RuntimeException. Example


Person p = new Person();
p.setName("something Bad);
entityManager.persst(p);

If for some reason p isn't able to be saved by the entity manager a runtime exception will be thrown. Being a seasoned EJB developer I'd use this exception to my advantage and let it trickle out to the container and roll back the managed transaction (I think this is beautiful, but I guess a thing of the past).


Groovy, grails, and even rails does this different. The way you know an entity is saved is by the return value on the entity.save() method. Lets use the example above in grails.


def p = new Person(name:"something bad")
p.save()


if for some reason p is unable to be saved we won't be notified by the above code, you actually have to do it like this:


def p = new Person(name:"something bad")
if ( !p.save()) { p.errors.each(log.error(it))}


What I find fascinating about this example is a statically typed language is actually less code than a dynamic one!

Thursday, January 31, 2008

Jetty & spring are awesome

One reason I love java is it has so many tools out there to solve the problems you need to solve. I needed to write a server-side app that was way under the scope of jBoss, so I downloaded Jetty and used spring.

For those who don't know, Jetty is a super fast and light weight servlet container that uses NIO heavily. For apps that don't need stuff like transactions its perfect. And pair that up with Spring and you have a super fast & lightweight app that still has very good design.

So check out Jetty and Spring.