Ajax application using CherryPy

Ajax application using CherryPy

Python: CherryPy


In recent years, web applications have moved away from the simple pattern of "HTML pages + refresh the whole page". This traditional scheme still works very well but users have become used to web applications that don't refresh the entire page. Broadly speaking, web applications carry code performed client-side that can speak with the backend without having to refresh the whole page. Ajax helps us do the same.

We will write a simple application which will find the square root of a number client-side. The application will perform four HTTP requests for calculating the square. For more details about CherryPy application with HTTP requests, see a previous article titled, REST application using CherryPy, the link of which is given at the end.

First save the below CSS code in a file 'style.css' which is present in the directory 'public/css'.

body { color: white; background-color: rgb(31, 44, 44); } #square-val { display: none; }

For the main page of the application we will use the jQuery framework out of simplicity but feel free to replace it with your favourite tool. The page is composed of simple HTML elements to get user input and display the generated string. It also contains client-side code to talk to the backend API that actually performs the hard work.

Save the below code in file 'index.html'.

<!DOCTYPE html> <html> <head> <link href="/static/css/style.css" rel="stylesheet" /> <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $("#calc-square").click(function (e) { $.post("/square", { number: $("input[name='number']").val(), }).done(function (square_val) { $("#square-val").show(); $("#square-val input").val(square_val); }); e.preventDefault(); }); $("#replace-val").click(function (e) { $.ajax({ type: "PUT", url: "/square", data: { number: $("#square-val input").val() }, }).done(function () { alert("Replaced!"); }); e.preventDefault(); }); $("#delete-val").click(function (e) { $.ajax({ type: "DELETE", url: "/square", }).done(function () { $("#square-val").hide(); }); e.preventDefault(); }); }); </script> </head> <body> <input type="text" value="2" name="number" /> <button id="calc-square">Calculate Square</button> <div id="square-val"> <input type="text" /> <button id="replace-val">Replace result</button> <button id="delete-val">Delete result</button> </div> </body> </html>

Finally we will write the application's code that serves the HTML page above and responds to requests to calculate the square of a number.

Save the below code in a file named 'ajax_app.py'.

import cherrypy import os class application: @cherrypy.expose def index(self): return open('index.html') @cherrypy.expose class applicationWebService: @cherrypy.tools.accept(media='text/plain') def GET(self): return cherrypy.session['ans'] def POST(self, number=2): answer = str(int(number)**2) cherrypy.session['ans'] = answer return cherrypy.session['ans'] def PUT(self, number): cherrypy.session['ans'] = number def DELETE(self): cherrypy.session.pop('ans', None) if __name__ == '__main__': conf = { '/': { 'tools.sessions.on': True, 'tools.staticdir.root': os.path.abspath(os.getcwd()) }, '/square': { 'request.dispatch': cherrypy.dispatch.MethodDispatcher(), 'tools.response_headers.on': True, 'tools.response_headers.headers': [('Content-Type', 'text/plain')], }, '/static': { 'tools.staticdir.on': True, 'tools.staticdir.dir': './public' } } webapp = application() webapp.square = applicationWebService() cherrypy.quickstart(webapp, '/', conf)

Run the code through the Terminal/Command Line as follows:

    python3 ajax_app.py

Now, if we enter http://localhost:8080/ in the address bar of a browser, the output will be something like this

Now we will call the square method with value, say, 9. The following output appears

We can perform the other HTTP requests, PUT and DELETE, by clicking on the buttons 'Replace result' and 'Delete result' respectively.


Link to the article 'REST application using CherryPy':


More Articles of Aniket Sharma:

Name Views Likes
Pyperclip: Installation and Working 990 2
Number Guessing Game using Python 683 2
Pyperclip: Not Implemented Error 1026 2
Hangman Game using Python 16785 2
Using Databases with CherryPy application 1672 2
nose: Working 506 2
pytest: Working 510 2
Open Source and Hacktoberfest 867 2
Managing Logs of CherryPy applications 1001 2
Top 20 Data Science Tools 684 2
Ajax application using CherryPy 799 2
REST application using CherryPy 663 2
On Screen Keyboard using Python 5508 2
Elastic Net Regression 815 2
US Presidential Election 2020 Prediction using Python 794 2
Sound Source Separation 1164 2
URLs with Parameters in CherryPy 1633 2
Testing CherryPy application 635 2
Handling HTML Forms with CherryPy 1448 2
Applications of Natural Language Processing in Businesses 508 2
NetworkX: Multigraphs 648 2
Tracking User Activity with CherryPy 1396 2
CherryPy: Handling Cookies 820 2
Introduction to NetworkX 633 2
TorchServe - Serving PyTorch Models 1301 2
Fake News Detection Model using Python 734 2
Keeping Home Routers secure while working remotely 483 2
Email Slicer using Python 2996 2
NetworkX: Creating a Graph 1108 2
Best Mathematics Courses for Machine Learning 551 2
Hello World in CherryPy 680 2
Building dependencies as Meson subprojects 978 2
Vehicle Detection System 1081 2
NetworkX: Examining and Removing Graph Elements 607 2
Handling URLs with CherryPy 536 2
PEP 8 - Guide to Beautiful Python Code 757 2
NetworkX: Drawing Graphs 623 2
Mad Libs Game using Python 643 2
Hosting Cherry applications 612 2
Top 5 Free Online IDEs of 2020 866 2
pytest: Introduction 534 2
Preventing Pwned and Reused Passwords 581 2
Contact Book using Python 2095 2
Introduction to CherryPy 547 2
nose: Introduction 505 2
Text-based Adventure Game using Python 3000 2
NetworkX: Adding Attributes 2278 2
NetworkX: Directed Graphs 1021 2
Dice Simulator using Python 560 2
Decorating CherryPy applications using CSS 833 2