Python web application CRUD sample using CherryPy and MongoDB database

  • A CRUD sample implemented using CherryPy framework and MongoDB database.
    All the CRUD operations are explained in detail with code samples.
    To connect to MongoDB, pymongo library is used.
    Complete the step by step tutorial to get familiarized with Python CherryPy web application development and MongoDB database integration.
    This sample lists a set of books available in a library. Users can add, edit or delete from this list.

  • Set up python in your machine

    Download and install the latest version of python from Python Website.

    Setting up virtual environment is not a must, but its is good to keep all your projects within a virtual environment. Here, we will proceed with a virtual environment.

    For that, go to the command prompt and cd to the folder where you are going to keep your project.
    Run command python -m venv book_library to create a virtual environment folder book_library. We will be keeping all our code in this folder and the installed package files will also be kept automatically within this folder.

    Now, activate the VE using command:

    For Windows:
    book_library\Scripts\activate.bat
    For Linux, macOS:
    source book_library /bin/activate

    After VE activation, from cmd type cd book_library to navigate to the project folder.

  • Install CherryPy and Jinja2 Template Engine

    To install CherryPy, run command pip install CherryPy or pip3.9 install CherryPy
    If not working use commands:

    For Windows:
    py -3.9 -m pip install CherryPy
    For Linux, macOS:
    python3.9 -m pip install CherryPy

    Also install Jinja2 using the command pip install Jinja2. Jinja2 is basically a template engine that helps in serving the html to the user. Using this library along with CherryPy helps in faster development. For example, we are using Jinja2 function get_template to render HTML page from the python code and python codes like for loops are added to the HTML page using the Jinja2 template markup syntax.

  • Install pymongo

    For MongoDB connection we are going to use the pymongo library. Install this using the command: pip install pymongo or pip3.9 install pymongo (If using 3.9 python version).

    Run pip freeze or pip3.9 freeze to check if all packages installed successfully.

  • Web Application Initial Setup

    Let us start with the initial set of code that is required for every CherryPy web applications. Create a file named books.py (you can provide any name) inside book_library folder and copy below code to it. books.py is going to contain your start-up code which is required to run the web app.
    Now, from command prompt navigate to book_library folder and execute command py books.py or python books.py or py -3.9 -m books or python3.9 -m books (Based on the Python version used and the Operating System).

    import cherrypy
    
    class BookLibrary(object):
        @cherrypy.expose
        def index(self):
            return 'Book Library app is starting up'
    
    if __name__ == '__main__':
        cherrypy.quickstart(BookLibrary())
    

    This code imports cherrypy module and then a startup class is created and initiated using the quickstart method from the __main__. Startup class should have a method named index that will load the first HTML content.
    In command prompt, we will see the below message when execution starts without any issues.

    	[08/Jun/2022:18:11:50] ENGINE Listening for SIGTERM.
    	[08/Jun/2022:18:11:50] ENGINE Bus STARTING
    	CherryPy Checker:
    	The Application mounted at '' has an empty config.
    
    	[08/Jun/2022:18:11:50] ENGINE Started monitor thread 'Autoreloader'.
    	[08/Jun/2022:18:11:50] ENGINE Serving on http://127.0.0.1:8080
    	[08/Jun/2022:18:11:50] ENGINE Bus STARTED
    

    Copy the URL http://127.0.0.1:8080 to your browser and run. The message Book Library app is starting up will display in the web browser, if the set up is proper and without any issues.

  • Setting up First page

    Now we are going to load an HTML file as the first page of the application.
    Create an HTML file bookslist.html inside book_library folder.

    Add below code to bookslist.html page.
    In books.py, add the line return open('bookslist.html') inside index function to render this HTML as the first page.

    Changes are automatically compiled and on refreshing the web page we can see the HTML page as the output.

  • MongoDB Database Setup

    We will use the PyMongo adapter to create database and a table and insert data to it.
    Create a file named mongodbData.py in the same code folder and paste the below code in it.
    Run this file using command py mongodbData.py or python mongodbData.py or py -3.9 -m mongodbData or python3.9 -m mongodbData.py

    This set of code connects to the local MongoDB client and then creates a database and a table in it. You should have MongoDB installed locally in your machine or use a valid server url in the below code.
    Then we are inserting five records to the table.

    Copied
    import pymongo
    
    booklibraryClient = pymongo.MongoClient("mongodb://localhost:27017/")
    booksDB = booklibraryClient["BookLibrary"]
    bookstable = booksDB["BooksTable"]
    
    bookslist = [
      { "ID": 1, "Name": "Harry Potter", "Year": 2020, "Price": 100 },
      { "ID": 2, "Name": "The Lord of the Rings", "Year": 2018, "Price": 80 },
      { "ID": 3, "Name": "The Alchemist", "Year": 2010, "Price": 85 },
      { "ID": 4, "Name": "The Da Vinci Code", "Year": 2017, "Price": 70 },
      { "ID": 5, "Name": "The Twilight Saga", "Year": 2015, "Price": 90 }
    ]
    
    tbl = bookstable.insert_many(bookslist)
    print(tbl.inserted_ids)
    
  • Read data from MongoDB and list

    bookslist.html is going to hold the list of books in the library. To list the items, add below code to the body of the HTML and modify books.py main method as below. Also import pymongo. In python file, we are reading data from MongoDB database BookLibrary using pymongo built-in functions as shown below and pass it to html as a parameter. In html, we are looping through the items and list it as table rows.

    For styling we will use Bootstrap 5. Add below 2 lines inside head of html.

    
        <link rel="stylesheet" crossorigin="anonymous"
    	href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" >
        
    	<script crossorigin="anonymous"
    	src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" >
    	</script>
    
    

    On reload, we will get below output window.

    CherryPy and MongoDB - List Items
  • Create or update record

    Add a new link button in the bookslist.html above the table.

        <a class="btn btn-primary" href="openaddbookpage/0">Add New Book</a>
    

    Add new html file, addbook.html and place the below code.
    Add two links for edit and delete in bookslist.html as below.
    Add two more route methods, openaddbookpage() and savebookdetails() in books.py below index() method to handle routing to the edit page and saving the data (Double check the pasted contents are properly intended).

    Add New Book button in the list page calls openaddbookpage route with ID as 0. So Book Details page opens in Create mode with empty text boxes.
    Edit link next to each row also calls openaddbookpage route, but passes ID number to the Book Details page. So the details of the selected book gets fetched from the DB and bind to the corresponding text boxes in the HTML page.

    savebookdetails route is called on Submit button click. If the entered ID number doesn't exist in the database, new book gets added using insert_one method. Otherwise, existing record is updated using update_one method.

    CherryPy and MongoDB - Add an Item
  • Delete a Record

    For delete, we will add a new route method deletebook() and call delete_one method to delete the selected ID.

    Copied
        @cherrypy.expose
        def deletebook(self, id=0):
            booksDB = connectDB()
            bookstable = booksDB["BooksTable"]
            bookstable.delete_one({ "ID": int(id) })
            raise cherrypy.HTTPRedirect("../")
    
  • CherryPy CRUD with MongoDB database - Complete code

    Complete code is placed below.

Absolute Code Works - Python Topics