Table of contents
1.
Introduction
2.
Database with Cherrypy
3.
Implementation
3.1.
CSS Program
3.2.
HTML Program
3.3.
Python Program
3.4.
Output
4.
Disadvantage of Using SQLite with Cherrypy
5.
Frequently Asked Questions
5.1.
What are the different database servers supported by Cherrypy?
5.2.
Is CherryPy a web server?
5.3.
What is a web server in Cherrypy?
5.4.
What happens after CherryPy expose is called?
6.
Conclusion
Last Updated: Mar 27, 2024

Data is all my life and manage with cherrypy

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

Introduction

We learned how to use Ajax to launch a straightforward application in the last tutorial. However, until this point, every created string was saved in the session. They are, by default, kept in the process memory. Even though we can save sessions on disc or in a distributed memory store, this is not the ideal method for storing data over the long term. Sessions are used to identify the user and carry only the information required for the user's task.

Database with Cherrypy

As was previously noted, "cherrypy.session" stores session data by default in the process memory. On the other hand, it is not the best strategy for long-term data storage. Sessions are used to identify users and transport only the data required for the actions the users are carrying out. A suitable database server is needed to store, persist, and query data. There are numerous options available with varying levels and types of support. The SQLite database with Cherrypy, which Python explicitly supports, will be used instead. This is also the case because it is a relational one. We will start with them since they are the most prevalent and easily understood.

Implementation

We will create a straightforward client-side application to calculate a number's cube. The application will take the place of an SQLite database. It is in which the computed cube from the session was previously stored. The application we produced in the earlier article is expanded upon in this application. See the link provided after the previous post titled "Make it smoother with Ajax in cherrypy" for further reference.

CSS Program

First, save the CSS code below in a file called "style.css" located in the "public/css" directory.

body {
  color: rgb(0, 0, 0);
  background-color: rgb(233, 185, 255);
}

#cubeValue {
  display: none;
}

HTML Program

For the sake of simplicity, the primary page of the programme will be built using the jQuery framework. We are allowed to use our preferred tool in its stead, however. Simple HTML elements are used on the page to collect user input and display the resulting string. Additionally, it has client-side code to communicate with the backend API that does the labour-intensive job. The code is identical to that discussed in our previous tutorial. It can be seen in our earlier article, "Make it smoother with Ajax in cherrypy."

Python Program

The code for the application that provides the abovementioned HTML page performs requests to find the cube of a number. It also saves those results in the database "mydatabase.db", which will be written in the last step.

import cherrypy
import sqlite3
import time
import os

DB_STRING = "mydatabase.db"

class application:
    @cherrypy.expose
    def index(home):
        return open('index.html')

@cherrypy.expose
class applicationWebService:

    @cherrypy.tools.accept(media='text/plain')
    def GET(home):
        with sqlite3.connect(DB_STRING) as c:
            cherrypy.session['ts'] = time.time()
            r = c.execute("SELECT value FROM user WHERE session_id=?",
                          [cherrypy.session.id])
            return r.fetchone()

    def POST(home, integer=3):
        answer = str(int(integer)**3)
        with sqlite3.connect(DB_STRING) as c:
            cherrypy.session['ts'] = time.time()
            c.execute("INSERT INTO user VALUES (?, ?)",
                      [cherrypy.session.id, answer])
        return answer

    def PUT(home, integer):
        with sqlite3.connect(DB_STRING) as c:
            cherrypy.session['ts'] = time.time()
            c.execute("UPDATE user SET value=? WHERE session_id=?",
                      [integer, cherrypy.session.id])

    def DELETE(home):
        cherrypy.session.pop('ts', None)
        with sqlite3.connect(DB_STRING) as c:
            c.execute("DELETE FROM user WHERE session_id=?",
                      [cherrypy.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())
        },
        '/cube': {
            '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.cube = applicationWebService()
    cherrypy.quickstart(webapp, '/', conf)
You can also try this code with Online Python Compiler
Run Code

The code should be saved in a file called "sql_app.py," as advised.
It is to be seen that we called the database in place of every session code. We need the session id to locate the user's string in our database with cherrypy. Since the session will eventually end, it is probably not the best course. Associating the user's login or a more durable unique identification would be a better idea. This should work for our demonstration purposes.
To prevent CherryPy from discarding the session on each request, we must still set the session, in this case, to a dummy value. We save a fake timestamp inside the session because we now use the database with cherrypy to store the created string.

Output

We run the code using the Terminal or Command Line as follows to obtain the output:     "python3 sql_app.py"
If the users go to "http://localhost:8080/" now, they can see that the values will be saved in the database "mydatabase.db". It will happen after the numbers have been cubed.

You can also read about the memory hierarchy.

Disadvantage of Using SQLite with Cherrypy

Unfortunately, Python's SQLite library restricts us from allowing threads to share a connection. This would be problematic as CherryPy is a multi-threaded server. We do this on each call by opening and closing a connection to the database with cherrypy. This is not very conducive to production. To better serve the requirements of our application, it is probably advisable to use a more competent database engine or a higher-level library, such as SQLAlchemy.

Frequently Asked Questions

What are the different database servers supported by Cherrypy?

There are numerous database servers available with different paradigm support. Cherrypy provides support for all of them. Example: 

relational: PostgreSQL, SQLite, Firebird, MariaDB
column-oriented: HBase, Cassandra
key-store: Memcached, Redis
document-oriented:MongoDB, CouchDB
graph-oriented: neo4j

Is CherryPy a web server?

CherryPy can be used as a standalone web server or in conjunction with any WSGI-compatible environment. It does not deal with things like output rendering templates or backend access. Filters can be added to the framework and are invoked at specific times throughout the processing of requests and responses.

What is a web server in Cherrypy?

Cherrypy's web server serves as the application's entry point. All requests and responses are handled by it.

What happens after CherryPy expose is called?

For Cherrypy, a developer's responsibility is to offer the tools necessary to implement the application's logic. After CherryPy has found and has called an exposed method, the application logic tools must be provided by the developer. In simple words, CherryPy holds the thought that developers are the experts.

Conclusion

Cherrypy is versatile and uses a database in a very efficient way. This makes it handy and easy to use. In the article, we created a simplistic client-side application that found a number's cube. An SQLite database with cherrypy is used in place of the application's previous method of storing calculated squares from sessions. Therefore shows the use of Cherrypy with a database in a real-world scenario.  You can read how to build applications with Python and find the basics of python here. Do not forget to check out more blogs on Cherrypy and Python to follow.

Thank you image

Explore Coding Ninjas Studio to find more exciting stuff. Happy Coding!

Live masterclass