Download Install Tutorial Docs FAQ Tools WikiLicense Team IRC Planet Involvement Shop Book

Intro to CherryPy

Lesson 1

Preface

If you like programming python and want to build web applications then you need to be able to map your python code to web pages. CherryPy enables you to do just that in an easy, clean and quick way. Today there are many python web frameworks that allow you to do that. In the face of so many python frameworks, which one should you choose, which one is best suited to you? The problem then is not one of lack, but of overabundance. The general problem with web frameworks is that if they are not kept simple and intuitive by design, then they gradually acquire a jungle of bells and whistles, a maze of features and intricacies, which create a big learning curve for programmers. And programmers don't generally want to learn the ins and outs of yet another proprietary system - it wastes their time, mind space and slows them down. Therefore a good choice would be a python web framework that is pythonic, i.e. light, clean, simple to understand, quick to get going with and powerful enough to allow you to work your python magic on the web. CherryPy fits the bill and therefore after much evaluation and experimentation I have decided to implement my python/web applications on CherryPy.

What is CherryPy?

In a nutshell, CherryPy allows you to "map" your python code to URLs. So basically you can pass data from web pages to your python classes and methods and pass it back to web pages. This enables you to create completely customized web applications. What is nice about CherryPy is that after some very basic configuration (which we will go through in this article) it stays out of your way, and it's all you, and your python code. And this is what is nice about CherryPy! CherryPy does have a host of more sophisticated features that may come in handy for specific tasks or for advanced requirements, but its good that these features are separated from basic usage, and a new user need not get bogged down, know, or care about these. And this is really the best of both worlds. Later when you need more advanced features, you know that CherryPy has them and you can look for them, but they will not interfere with getting going with developing your app rapidly in CherryPy. After all, time/life is precious and we don't have time to learn everything :)

Choosing a template language

While CherryPy will map your python objects to URLs, you still need to be able make HTML pages and mix these with python code in the best way possible. A templating system will do that for you.

Once you have chosen CherryPy as your python web development framework, there is one more choice to be made and that is the templating system. I know, you might be asking, "why isn't there ONE good way to do things", right? Why do we need a web framework and a templating system...? One of the purposes of this article is to cut out the information overload and present one simple straightforward way of getting going with cherrypy. Anyway, with templating systems, again there are many choices and they don't make things easier as one has to figure out which one to choose.

After a lot of research I chose Mako. You can choose any templating system you like, but Mako is simple to use, comprehensive and provides some powerful features that may come in handy later as your web app development moves along to deeper waters.

Download

Go to the download section in each of the following websites. Download the latest stable tar.gz files:

In order to install Mako you need to have a package called Beaker installed:

Install

Once you have the tar.gz files, unpack them using: tar -xzf filename.tar.gz

Thereafter, a folder with the same name as the tar.gz package will be created right next to the tar.gz package that you downloaded. Follow the instructions in the README.TXT to complete install. The instructions would generally tell you to run: python setup.py install. Once you do this for CherryPy and Mako, and they complete successfully, you are ready to go...

If you want to test your install, you can run the test file which comes with the install. Instructions on how to run the install tests are in the readme files.

Your development environment is now set up and you are ready to set up the files and directories that will get you started with a real application using Python, CherryPy and Mako.

Developing a simple web application

One of the reasons that I am writing this is because I found that there are several ways to accomplish similar things, and I wanted to know the most straightforward and cleanest way to go. Therefore, after some help from the CherryPy team, I was able to come up with a very simple way to set up my CherryPy files. In this section I share that with you.

The Application

The application is very simple, but illustrates how to use CherryPy, Mako and Python together in a real development environment. Starting from here you can add whatever functionality you would like to make your own custom applications. This application creates a hyperlink and upon clicking the hyperlink it redirects to another page. When one is not familar with the conventions of a development framework, upon first reading, one may confuse keywords defined by the user (i.e. you) with keywords used in the framework. In all of the following files I have preceded any keywords that can be defined by you with the words 'arjuna' indicating that these are names I have chosen. You can choose to substitute these with your own keywords that may be more meaningful to you and your application. This indicates which words are user defined and which belong to the framework.

Create the following files:

File 1: arjunaTest.html

<html><body>
        <a href="/arjunaOutputPage">Output</a>
</body></html>

File 2: arjunaTestOutput.html

<html><body>
         Hello ${arjunaName}
         Welcome to your very own ${arjunaWorld} !!
</body></html>

File 3: arjunathelinkapp.py

# Import the cherrypy and mako modules. If everything
# went ok in the install these should be
# available on your system

import cherrypy
from mako.template import Template
from mako.lookup import TemplateLookup


# TemplateLookup is a Mako object that specifies where mako
# is to find the html files you want to render. I recommend
# going through the Basic usage of Mako docs to get started:
# http://www.makotemplates.org/docs/usage.html. Mako does not
# need a full physical path and is able to understand a
# relative path from the location of the python file it has
# been imported into. Therefore specifying 'arjunhtml' below
# is enough and 'arjunhtml' is the subdirectory. So the
# python file sits in ..../arjunapyfiles then the 'arjunahtml'
# directory sits in ..../arjunapyfiles/arjunahtml for the
# below to work. You need to change this to suit your own
# directory structure. Or for a quick start, just create a
# subdirectory below where you put this python file and put
# the sub directory name instead of 'arjunahtml'

mylookup = TemplateLookup(directories=['arjunahtml'])

# The website. Remember, where ever you see the word 'arjuna...'
# you can put your own names.

class arjunaSampleApplication:

    # The @cherrypy.expose tells the server that this
    # method can be accessed from a webpage. We need to
    # put this before any method that we want to access
    # from a webpage
    
    @cherrypy.expose
    def index(self):
        # mylookup.get_template is mako functionality that
        # specifies the file you want to render. In this case
        # it pulls the file 'arjunaTest.html' from '/arjunahtml'
        
        mytemplate = mylookup.get_template("arjunaTest.html")
        
        # 'mytemplate.render()' is for rendering the file i.e.
        # doing any substitutions in it, and in this case,
        # creating a straight html file
        
        return mytemplate.render()

    @cherrypy.expose
    def arjunaOutputPage(self):
        # The 2 lines below get the page 'arjunaTestOutput.html'
        # and render it in the browser while passing the two
        # variables arjunaName and arjunaWorld
        # to the html file
        
        mytemplate=mylookup.get_template("arjunaTestOutput.html")
        return mytemplate.render(arjunaName="arjuna",
                                 arjunaWorld="planet of cherries")

# Everything below this is standard CherryPy-speak for getting things
# configured and started. You can safely put all this at the bottom of
# your python file and have it startup CherryPy correctly. However,
# remember that when you create your own application, you do have to
# change any keywords with the words 'arjuna...'  to point to your
# files or variables. All the non-'arjuna...' words are CherryPy-speak.


# Set up the site
cherrypy.config.update("arjunaGlobal.conf")

# Set up the application
arjunaroot = arjunaSampleApplication()
cherrypy.tree.mount(arjunaroot, '/', "arjunaApp.conf")

#start the server
cherrypy.server.quickstart()
cherrypy.engine.start()

File 4: arjunaglobal.conf

[global]
server.socket_host = "127.0.0.1"
server.socket_port = 8080
server.thread_pool = 10

File 5: arjunaApplication.conf

[/]
tools.staticdir.root = "/home/arjun/brahmaforces/source/arjunapyfiles"
# This is the physical path to the root of the site.
# You can substitute this with your own path.

Summary:

So you should have created the above 5 files. The .py file and two .conf files should sit in the directory you have chosen to be the root. In the root create a folder for the two html files, in this example it is called, 'arjunahtml'. Put the html files in this folder. And you are all set to go with your application...

Running our application

From the directory in which your python file lives, Just do:

python arjunathelinkapp.py

The server should say something like:

HTTP serving HTTP on http://127.0.0.1:8080

This means the server is running and port 8080 is listening.

From your browser go to http://localhost:8080/ You should see the link output. Upon clicking you should be directed to the second html page, arjunaTestOutput, with the variables 'name' and 'world' neatly substituted in. If you get any errors, check your code, and if you still can't get it to work, feel free to post your questions on http://groups.google.com/group/cherrypy-users

Going forward

Now that you have a CherryPy-Mako development environment going, here are some resources to help you build your python web application:

This is the first of a series of lessons for new users looking to do build python web apps using CherryPy. Other lessons are planned that will cover common tasks like building form widgets, authentication...

Good Luck!!!

Written by arjuna, http://www.brahmaforces.com

Hosted by WebFaction

Log in as guest/cpguest to create tickets