Introduction to CherryPy


With the growth of the internet, developing web applications has become crucial. Python has grown to be a well-liked option for web development because to its simplicity and dependability. CherryPy is one of its frameworks that makes this approach simple. With the use of real-world examples, this article introduces CherryPy, its features, and how to utilise them to create web applications.

What is CherryPy?

Python's CherryPy is a simple, object-oriented web framework. It adheres to the tenet that "everything is an object," making it a natural choice for developers accustomed to Python's object-oriented structure. It lets programmers to create web applications in a manner similar to that of object-oriented Python programmes, leading to smaller, more readable code.

Getting Started with CherryPy

Using pip, the package installer for Python, to install CherryPy is simple. Run this command to install it if you haven't already:

pip install cherrypy

When installed, use the following syntax to import it into your Python script:

import cherrypy

Building a Simple Web Application with CherryPy

The elegance of CherryPy is in its simplicity. Let's create a straightforward web application as an example.

Example 1: Hello World!

import cherrypy

class HelloWorld(object):
   @cherrypy.expose
   def index(self):
      return "Hello World!"

cherrypy.quickstart(HelloWorld())

This programme creates a straightforward web server that responds to requests with "Hello World!" The index method is made available to the web by the @cherrypy.expose decorator, making it accessible via a URL. The web server is started by cherrypy.quickstart().

Example 2: Working with HTTP Verbs

Additionally, CherryPy makes it straightforward to use HTTP verbs like GET and POST. Here's an illustration:

import cherrypy

class HelloWorld(object):
   @cherrypy.expose
   def index(self):
      if cherrypy.request.method == "GET":
         return "This was a GET request."
      elif cherrypy.request.method == "POST":
         return "This was a POST request."

cherrypy.quickstart(HelloWorld())

In this illustration, the index method determines if the incoming request is a GET or a POST request by checking the HTTP method and returning a different string accordingly.

Example 3: URL Parameters and Route Handling

With CherryPy, handling URL parameters and various routes is also simple:

import cherrypy

class HelloWorld(object):
   @cherrypy.expose
   def index(self, name="World"):
      return f"Hello {name}!"

   @cherrypy.expose
   def greet(self, name="Stranger"):
      return f"Nice to meet you, {name}."

cherrypy.quickstart(HelloWorld())

In this illustration, the response is customised using a URL parameter name that the index method supports. The default value is "World" if no name parameter is specified. The greet method receives a name parameter and indicates a separate route (/greet).

Example 4: Serving Static Files

Static files like scripts, stylesheets, and pictures can also be served using CherryPy. How would you go about setting that up?

import cherrypy

class HelloWorld(object):
   @cherrypy.expose
   def index(self):
      return open('index.html')

if __name__ == '__main__':
   conf = {
      '/': {
         'tools.staticdir.root': '/path/to/your/static/files',
      },
      '/static': {
         'tools.staticdir.on': True,
         'tools.staticdir.dir': 'public',
      }
   }
cherrypy.quickstart(HelloWorld(), '/', conf)

In this illustration, an HTML file is served through the index method. A static directory serving files from the public directory is created at the URL /static by the configuration conf.

Example 5: Implementing Cookies

CherryPy also provides easy handling of cookies −

import cherrypy

class HelloWorld(object):
   @cherrypy.expose
   def index(self):
      if cherrypy.request.cookie.get('name'):
         name = cherrypy.request.cookie['name'].value
         return f"Hello again, {name}!"
      else:
         cherrypy.response.cookie['name'] = 'Friend'
         cherrypy.response.cookie['name']['path'] = '/'
         cherrypy.response.cookie['name']['max-age'] = 3600
         return "Hello Stranger. I will remember you."
cherrypy.quickstart(HelloWorld())

The index method in this example determines whether a cookie with the name "name" already exists. If it does, the visitor is greeted by name; if not, the visitor is referred to as a stranger and the cookie is set.

Conclusion

A simple yet effective Python web framework, CherryPy is capable of handling a wide range of web development jobs. By using Python's object-oriented methodology, it makes web programming intuitive and straightforward. In addition to the routing, request processing, and response construction illustrated in these examples, it is also capable of doing more difficult jobs like delivering static files, controlling cookies, managing sessions, and more.

In this post, CherryPy was introduced and its core capabilities were examined using five examples: creating a simple web application, dealing with various HTTP methods, routing and URL parameters, delivering static files, and managing cookies.

Updated on: 17-Jul-2023

112 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements