Table of contents
1.
Introduction
2.
Set aliases to page handlers
3.
RESTful-style dispatching
3.1.
The special _cp_dispatch method
3.2.
The Popargs decorator
4.
Output
5.
Frequently Asked Questions
5.1.
What accomplishes CherryPy expose?
5.2.
CherryPy, a server for the web?
5.3.
CherryPy has several threads?
5.4.
Describe the CherryPy framework.
5.5.
Describe Falcon API.
6.
Conclusion
Last Updated: Mar 27, 2024
Medium

Set Aliases to Page Handlers in CherryPy

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this article, we will discuss why CherryPy? CherryPy is a Python-based framework that makes it simple for programmers to design and encapsulate web logic around HTTP protocols thanks to its Object Orientation approach. Why CherryPy's key strength is its simplicity. For database and templating purposes, it supports Object Relational Mapper (ORM) and extensions from templating languages. Now we look more into Why CherryPy?

cherrypy

Set aliases to page handlers

Support for aliases is a little-known but helpful functionality offered by the cherrypy.expose() decorator.

Alias

Let's apply the model from Tutorial #3:

import random
import string
import cherrypy
class StringGenerator(object):
    @cherrypy.expose(['generer', 'generar'])
    def generate(self, length=8):
        return ''.join(random.sample(string.hexdigits, int(length)))
        
if __name__ == '__main__':
    cherrypy.quickstart(StringGenerator())

 

For the page handler in this example, we build localised aliases. As a result, the page handler will be reachable through:

output
/generate
/generer (French) 
/generar(Spanish)


Naturally, you are free to choose any aliases that work best for you.

RESTful-style dispatching

When referring to friendly URLs that elegantly translate to the entities an application exposes, the phrase "RESTful URL" is sometimes used.

RESTful-style dispatching

Assume you want to develop a programme that makes music groups and their albums accessible. The following URLs are presumably present in your application:

http://hostname/<bandname>/
http://hostname/<bandname>/albums/<recordname>/

 

It's obvious that you wouldn't name a page handler after each and every band in the world. You will therefore require a page handler that serves as a proxy for each of them.

Page Handler

Because it requires page handlers to be explicitly stated in your source code, the default dispatcher is unable to handle that situation on its own. Fortunately, CherryPy has methods for supporting certain use situations.

The special _cp_dispatch method

Any of your controllers can declare the special method _cp dispatch to manipulate the remaining segments before CherryPy processes them. With this, you have the option to modify any segment any way you see fit and even change the remaining components totally.

import cherrypy
class Band(object):
    def __init__(self):
        self.albums = Album()
      def _cp_dispatch(self, vpath):
        if len(vpath) == 1:
            cherrypy.request.params['name'] = vpath.pop()
            return self
        if len(vpath) == 3:
            cherrypy.request.params['artist'] = vpath.pop(0)  # /band name/
            vpath.pop(0) # /albums/
            cherrypy.request.params['title'] = vpath.pop(0) # /album title/
            return self.albums
        return vpath
        
    @cherrypy.expose
    def index(self, name):
        return 'About %s...' % name
        
class Album(object):
    @cherrypy.expose
    def index(self, artist, title):
        return 'About %s by %s...' % (title, artist)
        
if __name__ == '__main__':
    cherrypy.quickstart(Band())


Pay attention to how the controller defines _cp dispatch; it only accepts one argument, the URL path information divided into its component parts.

The method has the ability to inspect and modify the segment list, deleting any and adding new segments at any location. The dispatcher will utilise the updated list of segments to find the right resource after receiving it.

The Popargs decorator

Since it offers a name to any section that CherryPy otherwise wouldn't be able to understand, cherrypy.popargs() is simpler. This facilitates the matching of segments with page handler signatures and aids CherryPy in comprehending the URL structure.

import cherrypy
@cherrypy.popargs('name')
class Band(object):
    def __init__(self):
        self.albums = Album()
    @cherrypy.expose
    def index(self, name):
        return 'About %s...' % name
        
@cherrypy.popargs('title')
class Album(object):
    @cherrypy.expose
    def index(self, name, title):
        return 'About %s by %s...' % (title, name)
if __name__ == '__main__':
    cherrypy.quickstart(Band())


Similar to _cp dispatch in operation, but more explicit and localised, as stated above. It reads:

  • the first segment should be saved in a parameter with the name band.
     
  • Since we eliminated the previous first, grab the first section once more and save it in a parameter called title.

It should be noted that the decorator takes multiple bindings. For illustration:

@cherrypy.popargs('title')
class Album(object):
    def __init__(self):
        self.tracks = Track()
        
@cherrypy.popargs('num', 'track')
class Track(object):
    @cherrypy.expose
    def index(self, name, title, num, track):

       
The following URL would be handled by this:

http://localhost:8080/nirvana/albums/nevermind/track/06/polly


Finally, take note of how each page handler receives the entire stack of segments, ensuring that you have the complete context.

Output

Output

Frequently Asked Questions

What accomplishes CherryPy expose?

In other words, it is your responsibility as a developer to offer the tools necessary to implement the logic of your application after CherryPy has been discovered and is called an exposed method. CherryPy believes that you, the developer, are the expert.

CherryPy, a server for the web?

In Brief CherryPy WSGI Web Server

Described as a fast, production-ready, thread-pooled, general HTTP server by the [CherryPy] team. Any Python WSGI web application can be served by this modular component.

CherryPy has several threads?

Application server with several threads. The multithreading idea served as the foundation for CherryPy's design. The multi-threaded environment is used each time a developer obtains or sets a value in the CherryPy namespace.

Describe the CherryPy framework.

The Python programming language is used by CherryPy, an object-oriented web application framework. By wrapping the HTTP protocol, it is intended to speed up the creation of web applications, although it remains low level and does not provide much more than what is specified in RFC 7231.

Describe Falcon API.

Falcon is a lightning-quick, lightweight Python web API framework for creating reliable app backends and microservices. The framework performs admirably with both gevent/meinheld and asyncio (ASGI) (WSGI).

Conclusion

We have talked about Set Aliases to Page Handler in cherryPy, their RESTful-style despatching the special_cp_dispatch method, etc.

You can also check the following articles:

If you face any doubt, please comment, and we will love to answer your questions.

Want expertise in Python for your next web development project? Check out our course.
Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass