Using Databases with CherryPy application

Using Databases with CherryPy application

Python: CherryPy


Storing the session data in cherrypy.session, which by default is stored in the process memory, is not the right way of keeping the data in the long run. Sessions are there to identify the users and carry as little amount of data as necessary for the operation carried by the users.

To store, persist and query data we need a proper database server. We will use the sqlite database which is directly supported by Python.

We will write a simple application which will find the square of a number client-side. The application will replace the storage of the calculated square from the session to a SQLite database. This application is an extension of the application we made in the previous article, for more details about it, see the previous article titled, Ajax 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=""></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 and stores them in the database 'my.db'.

Save the below code in a file named ''.

import cherrypy import os import sqlite3 import time DB_STRING = "my.db" class application: @cherrypy.expose def index(self): return open('index.html') @cherrypy.expose class applicationWebService:'text/plain') def GET(self): with sqlite3.connect(DB_STRING) as c: cherrypy.session['ts'] = time.time() r = c.execute("SELECT value FROM user WHERE session_id=?", []) return r.fetchone() def POST(self, number=2): answer = str(int(number)**2) with sqlite3.connect(DB_STRING) as c: cherrypy.session['ts'] = time.time() c.execute("INSERT INTO user VALUES (?, ?)", [, answer]) return answer def PUT(self, number): with sqlite3.connect(DB_STRING) as c: cherrypy.session['ts'] = time.time() c.execute("UPDATE user SET value=? WHERE session_id=?", [number,]) def DELETE(self): cherrypy.session.pop('ts', None) with sqlite3.connect(DB_STRING) as c: c.execute("DELETE FROM user WHERE session_id=?", []) def setup_database(): """ Create the `user` table in the database on server startup """ with sqlite3.connect(DB_STRING) as con: con.execute("CREATE TABLE user (session_id, value)") def cleanup_database(): """ Destroy the `user` table from the database on server shutdown. """ with sqlite3.connect(DB_STRING) as con: con.execute("DROP TABLE user") 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' } } cherrypy.engine.subscribe('start', setup_database) cherrypy.engine.subscribe('stop', cleanup_database) webapp = application() webapp.square = applicationWebService() cherrypy.quickstart(webapp, '/', conf)

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


Now, by going to the URL http://localhost:8080/ and calculating the square of some numbers, we can see that the values are being stored in the database 'my.db'.


Link to the article 'Ajax 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 1673 2
nose: Working 507 2
pytest: Working 511 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 664 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 509 2
NetworkX: Multigraphs 648 2
Tracking User Activity with CherryPy 1397 2
CherryPy: Handling Cookies 820 2
Introduction to NetworkX 633 2
TorchServe - Serving PyTorch Models 1302 2
Fake News Detection Model using Python 734 2
Keeping Home Routers secure while working remotely 484 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 608 2
Handling URLs with CherryPy 536 2
PEP 8 - Guide to Beautiful Python Code 757 2
NetworkX: Drawing Graphs 624 2
Mad Libs Game using Python 643 2
Hosting Cherry applications 613 2
Top 5 Free Online IDEs of 2020 867 2
pytest: Introduction 534 2
Preventing Pwned and Reused Passwords 582 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 2279 2
NetworkX: Directed Graphs 1021 2
Dice Simulator using Python 560 2
Decorating CherryPy applications using CSS 833 2