CherryPy - A Working Application


Full stack applications provide a facility to create a new application via some command or execution of the file.

Consider the Python applications like web2py framework; the entire project/application is created in terms of MVC framework. Likewise, CherryPy allows the user to set up and configure the layout of the code as per their requirements.

In this chapter, we will learn in detail how to create CherryPy application and execute it.

File System

The file system of the application is shown in the following screenshot −

File System

Here is a brief description of the various files that we have in the file system −

  • − Every application needs a configuration file and a way to load it. This functionality can be defined in

  • − MVC is a popular design pattern followed by the users. The is where all the objects are implemented that will be mounted on the cherrypy.tree.

  • − This file interacts with the database directly for some services or for storing persistent data.

  • − This file interacts with production ready web server that works properly with load balancing proxy.

  • Static − It includes all the CSS and image files.

  • Views − It includes all the template files for a given application.


Let us learn in detail the steps to create a CherryPy application.

Step 1 − Create an application that should contain the application.

Step 2 − Inside the directory, create a python package corresponding to the project. Create gedit directory and include file within the same.

Step 3 − Inside the package, include file with the following content −

#!/usr/bin/env python

import cherrypy

class Root(object):

   def __init__(self, data): = data

   def index(self):
      return 'Hi! Welcome to your application'

def main(filename):
   data = {} # will be replaced with proper functionality later

   # configuration file
      'tools.encode.on': True, 'tools.encode.encoding': 'utf-8',
      'tools.decode.on': True,
      'tools.trailing_slash.on': True,
      'tools.staticdir.root': os.path.abspath(os.path.dirname(__file__)),

   cherrypy.quickstart(Root(data), '/', {
      '/media': {
         'tools.staticdir.on': True,
         'tools.staticdir.dir': 'static'
if __name__ == '__main__':

Step 4 − Consider an application where the user inputs the value through a form. Let’s include two forms — index.html and submit.html in the application.

Step 5 − In the above code for controllers, we have index(), which is a default function and loads first if a particular controller is called.

Step 6 − The implementation of the index() method can be changed in the following way −

   def index(self):
      tmpl = loader.load('index.html')
      return tmpl.generate(title='Sample').render('html', doctype='html')

Step 7 − This will load index.html on starting the given application and direct it to the given output stream. The index.html file is as follows −


<!DOCTYPE html >
   <body class = "index">
      <div id = "header">
         <h1>Sample Application</h1>
      <div id = "footer">

Step 8 − It is important to add a method to the Root class in if you want to create a form which accepts values such as names and titles.

   def submit(self, cancel = False, **value):
      if cherrypy.request.method == 'POST':
         if cancel:
            raise cherrypy.HTTPRedirect('/') # to cancel the action
         link = Link(**value)[] = link
         raise cherrypy.HTTPRedirect('/')
      tmp = loader.load('submit.html')
      streamValue = tmp.generate()
      return streamValue.render('html', doctype='html')

Step 9 − The code to be included in submit.html is as follows −

<!DOCTYPE html>
      <title>Input the new link</title>
   <body class = "submit">
      <div id = " header">
         <h1>Submit new link</h1>
      <form action = "" method = "post">
         <table summary = "">
               <th><label for = " username">Your name:</label></th>
               <td><input type = " text" id = " username" name = " username" /></td>
               <th><label for = " url">Link URL:</label></th>
               <td><input type = " text" id=" url" name= " url" /></td>
               <th><label for = " title">Title:</label></th>
               <td><input type = " text" name = " title" /></td>
                  <input type = " submit" value = " Submit" />
                  <input type = " submit" name = " cancel" value = "Cancel" />
      <div id = "footer">

Step 10 − You will receive the following output −

File System Output

Here, the method name is defined as “POST”. It is always important to cross verify the method specified in the file. If the method includes “POST” method, the values should be rechecked in the database in appropriate fields.

If the method includes “GET” method, the values to be saved will be visible in the URL.