Basic concept on CherryPy

A python script called hello.py is created as follows:

import cherrypy

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

cherrypy.quickstart(HelloWorld())

The application can be started at the command prompt by typing $ python hello.py
At the web browser, “Hello World” can be seen when it is directed to http://localhost:8080.

import cherrypy // imports the main CherryPy module

class HelloWorld: //declare a class named HelloWorld
def index(self): // contains a single method called index which will be called when the root URL for the site is requested (http://localhost/)
return “Hello world!” // return the contents of the web page (“Hello world!” string)
index.exposed = True // to tell CherryPy that index() method will be exposed and only exposed methods can be called to answer a request. This allows user to select which methods will be accessible via the web.

cherrypy.quickstart(HelloWorld()) // mounts an instance of the HelloWorld class and starts the embedded webserver. It will run until explicitly interrupted.

When the web application is executed, the CherryPy server will listen on localhost at port 8080.
The default configuration of CherryPy server can be overridden by using another configuration file or dictionary.

When it receives the request for the URL http://localhost:8080, it searches for the best method to handle the request, starting from the first instance (HelloWorld). The root of the site is automatically mapped to the index() method. The HelloWorld class defines an index() method and exposes it (@cherrypy.expose). Therefore CherryPy will call HelloWorld().index() and the result of the call is returned to the browser as the contents of the index page for the website.

In order for CherryPy to call a page handler, it has to identify which and where to call for a given Uniform Resource Identifier (URI). A Dispatcher object is used to understand the arrangement of handlers and to find the appropriate page handler function.
The arrangement of CherryPy handler by default is a tree which enables the config to be attached to a node in the tree and cascade down to all children of that node. The mapping of URI to handlers is not always 1:1 and thus it offers more flexibilities.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s