Table of contents
1.
Introduction🗒
2.
Custom Processors.💻
3.
Frequently Asked Questions
3.1.
What is CherryPy, and what are the basic functionalities of CherryPy?
3.2.
How do you use CherryPy in Python?
3.3.
What do you mean by the Dispatcher in CherryPy?
3.4.
What is Falcon API?
3.5.
Why is the Falcon framework used?
4.
Conclusion
Last Updated: Mar 27, 2024
Medium

Request Body Processors in CherryPy

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

Introduction🗒

Hello Ninjas,

I know you have knowledge of Request Body Processors in CherryPy. And If you don't know anything about the Request Body Processors in CherryPy, don't worry. Because in this article, we will discuss the Request Body Processors in CherryPy.

So, before this, let's briefly discuss CherryPy.

CherryPy is an open-source framework that can extend and plug new functions at will, either server-side or on a per-request basis. CherryPy is made to help us to build our application and support our architecture via simple patterns.

CherryPy provides an elegant and powerful mechanism to deal with a request's body based on its mimetype.

The application authors have complete control over the parsing of HTTP request entities or, in short, we can say that the cherrypy.request.body is always set to an instance of RequestBody.

It is desirable to provide the information about the HTTP request, which includes an entity-body to applications in a form different from the raw bytes. Let's see an example where different content types demand different approaches.

  • The raw bytes should be in a stream for GIF Files.
  • An HTML form is parsed into its component fields, and each text field is decoded from bytes to Unicode.
  • And the JSON body should be deserialized into a Python dict or list.

 

Let's understand how to implement our process for any specific or significant MIME type.

Custom Processors.💻

Custom Processors Image

We can add it to the processors dict in a hook/tool that runs at on_start_resource or before_request_body. 

Let's take an example of the built-in JSON tool.

def json_in(force=True, debug=False):
    request = cherrypy.serving.request
    def json_processor(entity):
        '''Read application/json data into request.json.'''
        if not entity.headers.get("Content-Length", ""):
            raise cherrypy.HTTPError(411)
        body = entity.fp.read()
        try:
            request.json = json_decode(body)
        except ValueError:
            raise cherrypy.HTTPError(400, 'Invalid JSON document')
    if force:
        request.body.processors.clear()
        request.body.default_proc = cherrypy.HTTPError(
            415, 'Expected an application/json content type')
    request.body.processors['application/json'] = json_processor
You can also try this code with Online Python Compiler
Run Code


We can define a customer processor without making a Tool. We have to add the config entry:

request.body.processors = {'application/json': json_processor}
You can also try this code with Online Python Compiler
Run Code

 

This way, we can only replace the processors dict but not update the existing ones.

class cherrypy._cpreqbody.Entity(fp, headers, params=None, parts=None)
You can also try this code with Online Python Compiler
Run Code

 

The above class will collect information about the HTTP request entity. But when a given entity is of MIME type "multipart," each Part is parsed into its Entity instance, and the set of elements stored in entity.parts.

CherryPy tries to process the request body Between the before_request_body and before_handler tools by calling request.body.process. It uses the content_type of the entity to look up a suitable processor in entity.processors, a dict. If a matching processor cannot be found for the complete Content-Type, it tries again using the significant type. 

We know that CherryPy 3.2 processes these types almost exactly as older versions. If given, parts are passed as arguments to the page handler using their Content-Disposition.name. Otherwise, Each such Part is either a string or the Part itself in a generic "parts" argument if it's a file. (In this case, it will have file and filename attributes, or possibly a value attribute). Each Part is a subclass of entity, with its process method and processors dict.

A separate processor for the "multipart" significant type is more flexible and simply stores all multipart parts in request.body.parts. We can enable it with-

cherrypy.request.body.processors['multipart'] =_cpreqbody.process_multipart
You can also try this code with Online Python Compiler
Run Code

 

Let's see some built-in JSON on_start_resource tool.

built in json tools


Let’s see some built-in JSON on_start_resource tool.

built-in JSON tool table

We have discussed the Request Body Processors in CherryPy and also cover the Custom Processors. Now. Let's see some FAQs related to the Request Body Processors in CherryPy.

Frequently Asked Questions

What is CherryPy, and what are the basic functionalities of CherryPy?

CherryPy is the oldest Python framework used to build web applications. It provides basic functionalities like Create, Retrieves, Update and Delete.

How do you use CherryPy in Python?

CherryPy provides the CRUD (Create, Retrieve, Update and Delete) functionalities for applications and helps to manage the project from anywhere using the user's browser.

What do you mean by the Dispatcher in CherryPy?

A 'dispatcher' is the object which looks up the 'page handler' callable and collects config for the current request based on the path_info.

What is Falcon API?

Falcon is a blazingly fast, minimalist Python web API framework for building robust app backends and microservices. The framework works excellent with both (ASGI) and (WSGI).

Why is the Falcon framework used?

Falcon is a lightweight Python web framework for building high-performance microservices, app backends, and higher-level frameworks.

Conclusion

We have discussed the Request Body Processors in CherryPy and how to implement our process for any specific or significant MIME type with some FAQs related to the Request Body Processors in CherryPy.

After reading about the Request Body Processors in CherryPy, are you not feeling excited to read/explore more articles on Data Structures and Algorithms? Don't worry; Coding Ninjas has you covered. See Basics of PythonPythonweb2pyDjangoTesting Framework in PythonFlask Deployment, and Web Technologies to learn.

You can also check out these links Why CherryPyHow to Deploy Python WSGI Applications Using a CherryPyDeploy in CherryPyTailored in CherryPy, and Tools in CherryPy to know more in CherryPy.

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

Happy Learning!

Live masterclass