CherryPy(thon)

Posted by: v0id in PythonCherryPy on

I discussed the process of generating HTML-pages using templates in my previous blog entry, now we'll go a step further and let the output be used by a server, instead of manually getting the output, and save it as a HTML-file. For this purpose we'll use CherryPy, which is a web development framework for Python. It's not just a framework; it can also work as an server itself. That is primary advantage we're going to care about for now.

The most important function we're going to use is quickstart. It takes an instance of a class as parameter (and eventually other parameters as well, but we'll only use this one). The first thing we're going to do is to make the class we're going to pass to the function. The class has to have a member called index, which will be the function called by quickstart.

import cherrypy
# ...
class RSSApp:
    def index(self):
        # ...
        return str(template)


It's all the data returned by a specific function which will be outputted by CherryPy, so therefore does index return template. template is taken from my previous blog entry, so it contains the generated HTML.

This will not work yet, though. We have to expose the function before it can be used (if the index function isn't exposed a NotFound exception will be raised). There is two ways to expose a function: using a member variable or a special decorator. The former shall be putted right after the function has been implemented, while the latter shall be in front of it. They looks like the following, respectively:

# Former
index.exposed = True

# Latter
@cherrypy.expose


Now we're ready to start our application, so we return to the earlier mentioned quickstart function.

cherrypy.quickstart(RSSApp())

When the script runs, you shall open your favorite browser and point it to http://localhost:8080/, and you'll see the result. Note that the port-number may vary from configurations to configurations. Also, the information about where it shall be run, can be changed using special configuration files, which will not be covered here, though.
Trackback(0)
Comments (1)add comment

v0id said:

Ubuntu and Debian users can easily get and install CherryPy using apt-get.

$ sudo apt-get install python-cheerypy3
 
report abuse
vote down
vote up
June 03, 2008 | url
Votes: +2

Write comment
quote
bold
italicize
underline
strike
url
image
quote
quote
smile
wink
laugh
grin
angry
sad
shocked
cool
tongue
kiss
cry
smaller | bigger

busy