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);
}
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:
def index(self):
return open('index.html')
class applicationWebService:
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':
https://cppsecrets.com/users/5617971101051071011161151049711410997484852494964103109971051084699111109/REST-application-using-CherryPy.php
Comments