Perform addition and subtraction using CherryPy


CherryPy, a versatile Python web framework, offers a convenient and efficient way to perform addition and subtraction operations. In this article, we delve into the process of utilizing CherryPy to carry out basic arithmetic calculations within a web application.

By leveraging CherryPy's lightweight and intuitive features, developers can effortlessly implement addition and subtraction functionalities, making mathematical operations seamless and easily accessible to users.

How to perform addition and subtraction using CherryPy?

Below are the steps that we will follow to perform addition and subtraction using CherryPy −

  • We import the CherryPy module, which allows us to create a web application.

  • We define a class called `Calculator` that represents our web application. Inside this class, we define three methods − `index`, `add`, and `subtract`.

  • The `index` method is the default method that will be called when we visit the root URL of our web application (`http://localhost:8080`). It simply returns a welcome message.

  • The `add` method is decorated with `@cherrypy.expose`, which means it can be accessed via a URL. It takes two parameters, `a` and `b`, representing the numbers to be added.

  • Inside the `add` method, we check if both `a` and `b` have been provided. If not, we return a message asking the user to provide two numbers.

  • If both `a` and `b` are provided, we attempt to convert them into integers and perform the addition operation.

  • If the conversion and addition are successful, we return a message displaying the sum of `a` and `b`.

  • If there is an error during the conversion or addition (e.g., if the user provides non-numeric inputs), we catch the `ValueError` and return an error message.

  • The `subtract` method follows a similar structure as the `add` method, but it performs subtraction instead of addition.

  • We start the CherryPy server and bind the `Calculator` class to it using `cherrypy.quickstart`.

To run the program

  • Install CherryPy using

pip install cherrypy
  • Save the code in a Python file, for example, `calculator.py`.

  • Open a command prompt or terminal and navigate to the directory where the `file_name.py` file is located.

  • Run the program using `python calculator.py`.

  • Open a web browser and visit `http://localhost:8080` to see the welcome message.

  • To perform addition, visit `http://localhost:8080/add?a=<numbe>&b=<numbe>`, replacing `<numbe>` with the desired values for 'a' and 'b'.

  • The result of the addition operation will be displayed in your browser.

  • To perform subtraction, visit `http://localhost:8080/subtract?a=<numbe>&b=<numbe>`, replacing `<numbe>` with the desired values for 'a' and 'b'.

  • The result of the subtraction operation will be displayed in your browser.

Below is the program using the above steps −

Example

import cherrypy

class Calculator:
   @cherrypy.expose
   def index(self):
      return "Welcome to the Calculator!"

   @cherrypy.expose
   def add(self, a=None, b=None):
      if a is not None and b is not None:
         try:
            result = int(a) + int(b)
            return f"The sum of {a} and {b} is: {result}"
            except ValueError:
             return "Invalid input. Please provide valid numbers."
      else:
            return "Please provide two numbers for addition."

   @cherrypy.expose
   def subtract(self, a=None, b=None):
      if a is not None and b is not None:
         try:
               result = int(a) - int(b)
               return f"The difference between {a} and {b} is: {result}"
         except ValueError:
               return "Invalid input. Please provide valid numbers."
      else:
            return "Please provide two numbers for subtraction."

if __name__ == '__main__':
   cherrypy.quickstart(Calculator())

Output

Open the terminal and type python file_name.py and press enter it will give the following output −

C:\Users\Tutorialspoint>python mtt.py
[26/May/2023:16:19:13] ENGINE Listening for SIGTERM.
[26/May/2023:16:19:13] ENGINE Bus STARTING
[26/May/2023:16:19:13] ENGINE Set handler for console events.
CherryPy Checker:
The Application mounted at '' has an empty config.

[26/May/2023:16:19:13] ENGINE Started monitor thread 'Autoreloader'.
[26/May/2023:16:19:13] ENGINE Serving on http://127.0.0.1:8080
[26/May/2023:16:19:13] ENGINE Bus STARTED
127.0.0.1 - - [26/May/2023:16:19:26] "GET / HTTP/1.1" 200 26 "" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36"
127.0.0.1 - - [26/May/2023:16:19:40] "GET /add?a=5&b=3 HTTP/1.1" 200 24 "" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36"
127.0.0.1 - - [26/May/2023:16:19:49] "GET /subtract?a=8&b=2 HTTP/1.1" 200 36 "" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36"

Open the browser and type http://localhost:8080 it will open the following window −

Open the browser and type http://localhost:8080/add?a=5&b=3 it will open the following window −

Open the browser and type http://localhost:8080/subtract?a=8&b=2 it will open the following window −

Conclusion

In conclusion, CherryPy provides a convenient and efficient solution for performing addition and subtraction operations within web applications. By leveraging its lightweight features and intuitive framework, developers can easily implement these mathematical functionalities. CherryPy empowers web applications to seamlessly incorporate arithmetic calculations, enhancing user experience and overall functionality.

Updated on: 24-Jul-2023

72 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements