Table of contents
1.
Introduction
2.
Tools
2.1.
Output
3.
Stateful Tools
4.
Toolboxes
5.
Frequently Asked Questions
5.1.
What is CherryPy?
5.2.
What is CherryPy WSGI Web Server?
5.3.
What is the purpose of multi-threading in CherryPy?
5.4.
What is the CherryPy framework?
5.5.
What accomplishes CherryPy expose?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Tools in CherryPy

Author Saksham Gupta
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

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. CherryPy's key strength is its simplicity. It supports Object Relational Mapper (ORM) and extensions from templating languages for database and templating purposes. Now we look more into different tools in CherryPy.

Tools in CherryPy

Tools

The simplest callable object (function, method, or object implementing a __call__ method) is a tool, and it is fastened to a hook point. After the page handler was called, a straightforward tool was connected to the ‘example’ hook point, as seen below:

@cherrypy.tools.register('example')
def logit():
   print(cherrypy.request.remote.ip)


Additionally, tools can be manually assigned and developed. The equivalent of the decorator registration is:

cherrypy.tools.logit = cherrypy.Tool('example', logit)


But how will I use the tool?

The steps to using that tool are as follows:

class Root(object):
    @cherrypy.expose
    @cherrypy.tools.logit()
    def index(self):
        return "Tool Working."

Output

8

** Output can range from 6 to 102. 8 is for representation purposes**

Point to be Noted

The tool's name doesn't need to coincide with the callable's name. Technically the attribute assigned to cherrypy.tools. However, the tool will be referred to by that name in the settings.

Stateful Tools

Stateful Tools

Rich per-request functionality is made possible by the mechanism of the tool, which is incredibly adaptable.

In most cases, simple tools like those in the previous section suffice. On the other hand, if your workflow requires some sort of state during the request processing, you'll typically favour a class-based approach:

import time
import cherrypy

class ExampleTool(cherrypy.Tool):
    def __init__(self):
        cherrypy.Tool.__init__(self, 'example1',
                               self.start_timer,
                               priority=102)
    def _setup(self):
        cherrypy.Tool._setup(self)
        cherrypy.request.hooks.attach('example2',
                                      self.end_timer,
                                      priority=6)
    def start_timer(self):
        cherrypy.request._time = time.time()
        
    def end_timer(self):
        duration = time.time() - cherrypy.request._time
        cherrypy.log("Tike taken is%.4f" % duration)

cherrypy.tools.eg = ExampleTool()


What does this tool do?

This tool calculates how long the page handler needs to process a particular request. Right after the handler provides its result, it notes the time difference and stores the time at which the handler is about to be called.

The important part is that you can register for a hook point using the cherrypy.Tool function Object() { [native code] }, you must use the cherrypy.request.hooks.attach method to attach the same tool to a different hook point. When CherryPy applies the tool to the request, it immediately invokes the cherrypy.Tool.Setup method.

How to use it?

You can use it by adding this to your code.

@cherrypy.tools.eg()

Toolboxes

A toolbox called cherrypy.tools contains all of the CherryPy built-in tools. It reacts to configuration settings in the namespace "tools." As mentioned above, you can add your own Tools to this Toolbox.

Toolboxes


If you require greater modularity, you can even create your own Toolboxes. For instance, you may publish a collection of Tools for authentication and permission that everyone can use, or you might develop several Tools for working with JSON (hint, hint). Simple steps to create a new Toolbox are as follows:

import cherrypy

# You can create a new toolbox like this
newtools = cherrypy._cptools.Toolbox("newauth")

# You can add a tool to the toolbox like this
@newtools.register('before_request_body')
def check_access(default=False):
    if not getattr(cherrypy.request, "userid", default):
        raise cherrypy.HTTPError(404)

Frequently Asked Questions

What is CherryPy?

CherryPy is a very famous Python framework. Web applications can be constructed or built faster and more reliably with CherryPy. It's also known as a web application library based on OOPs. It is used for simplicity, resulting in minor source code in less time.

What is CherryPy WSGI Web Server?

It is described as a fast, production-ready, thread-pooled, general HTTP server by the [CherryPy] team. This modular component can serve any Python WSGI web application.

What is the purpose of multi-threading in CherryPy?

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.

What is 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.

What accomplishes CherryPy expose?

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.

Conclusion

In this article, we discussed Tools in CherryPy and saw stateful tools and toolboxes. To learn more about CherryPy.

You can refer to 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