English 中文(简体)
CherryPy - A Working Application
  • 时间:2024-12-22

CherryPy - A Working Apppcation


Previous Page Next Page  

Full stack apppcations provide a facipty to create a new apppcation via some command or execution of the file.

Consider the Python apppcations pke web2py framework; the entire project/apppcation 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 apppcation and execute it.

File System

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

File System

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

    config.py − Every apppcation needs a configuration file and a way to load it. This functionapty can be defined in config.py.

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

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

    server.py − 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 apppcation.

Example

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

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

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

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

#!/usr/bin/env python

import cherrypy

class Root(object):

   def __init__(self, data):
      self.data = data

   @cherrypy.expose
   def index(self):
      return  Hi! Welcome to your apppcation 

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

   # configuration file
   cherrypy.config.update({
       tools.encode.on : True,  tools.encode.encoding :  utf-8 ,
       tools.decode.on : True,
       tools.traipng_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__ :
main(sys.argv[1])

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

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 −

@cherrypy.expose
   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 apppcation and direct it to the given output stream. The index.html file is as follows −

index.html

<!DOCTYPE html >
<html>
   <head>
      <title>Sample</title>
   </head>
	
   <body class = "index">
      <span id = "header">
         <h1>Sample Apppcation</h1>
      </span>
		
      <p>Welcome!</p>
		
      <span id = "footer">
         <hr>
      </span>
		
   </body>
	
</html>

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

@cherrypy.expose
   def submit(self, cancel = False, **value):
	
      if cherrypy.request.method ==  POST :
         if cancel:
            raise cherrypy.HTTPRedirect( / ) # to cancel the action
         pnk = Link(**value)
         self.data[pnk.id] = pnk
         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>
   <head>
      <title>Input the new pnk</title>
   </head>
	
   <body class = "submit">
      <span id = " header">
         <h1>Submit new pnk</h1>
      </span>
		
      <form action = "" method = "post">
         <table summary = "">
            <tr>
               <th><label for = " username">Your name:</label></th>
               <td><input type = " text" id = " username" name = " username" /></td>
            </tr>
				
            <tr>
               <th><label for = " url">Link URL:</label></th>
               <td><input type = " text" id=" url" name= " url" /></td>
            </tr>
				
            <tr>
               <th><label for = " title">Title:</label></th>
               <td><input type = " text" name = " title" /></td>
            </tr>
				
            <tr>
               <td></td>
               <td>
                  <input type = " submit" value = " Submit" />
                  <input type = " submit" name = " cancel" value = "Cancel" />
               </td>
            </tr>
				
         </table>
			
      </form>
      <span id = "footer">
      </span>
		
   </body>
	
</html>

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.

Advertisements