Binding a list of items to an HTML page in CherryPy web app

  • In this topic, we will see how to display a list of items that we have in our Python (.py) server side code to the HTML front-end page, for a web application developed using Python CherryPy framework.
    Data can come from any kind of database or may be from a pre-defined list within the application (For CRUD samples utilizing different kinds of databases, you can refer the links on the right side of this page).
    In this sample, we are going to keep a list of items in JSON format in a separate JSON file.

  • Python libraries required

    Following python libraries are to be installed to run this sample.

    CherryPy: An object-oriented web application framework to develop python based web application. Install this using the command pip install CherryPy

    Jinja2: A template engine for Python. Jinja2 helps in serving the html to the user. Using this library along with CherryPy helps in faster code development.
    Jinja2 function get_template is used here to render HTML page from the python code. And, to list the items in the HTML page, we are including a Python for loop using the Jinja2 template markup syntax.
    Install using the command pip install Jinja2

  • JSON data to list

    Here, we are keeping the list of items in a JSON file named items.json. Create this file and copy below content.

    Copied
    [ 
        {"id":"1", "name":"James", "age":"25"},
        {"id":"2", "name":"Nicole", "age":"26"},
        {"id":"3", "name":"Ivan", "age":"27"},
        {"id":"4", "name":"Sara", "age":"28"}
    ]
    
  • HTML Code

    In the HTML page, we are using a table to list the data. With the help of Jinja2 template engine, we can include a Python for loop that repeats table rows in the HTML, as per the number of rows.
    Create a file listitems.html and copy below content.

    Copied
    <!DOCTYPE html>
    <html lang="en-US" dir="ltr">
    <head>
        <title>List Sample</title>
        <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>
    </head>
    
    <body>
        <h2>List Sample</h2>
        <table class="table">
            <thead>
                <tr>
                <th scope="col">Id</th>
                <th scope="col">Name</th>
                <th scope="col">Age</th>
                </tr>
            </thead>
            <tbody>
                {% for emp in emps %}
                    <tr>
                        <td>{{ emp.id }}</th>
                        <td>{{ emp.name }}</td>
                        <td>{{ emp.age }}</td>
                    </tr>
                {% endfor %}
            </tbody>
        </table>
    </body>
    

    For styling we are using Bootstrap 5 CSS and JS references.

  • Python Code

    In the python file, import cherrypy and jinja2 packages.
    Then create a startup class ListSample and initiate this class using the quickstart method from the __main__. Startup class should have a method named index that will load the first HTML content.
    In index() method, read data from the JSON file and pass to the html file using the Jinja2 template function get_template().
    Copy below code to a python file list.py.

    Copied
    import cherrypy
    import json
    import os
    from jinja2 import Environment, FileSystemLoader
    
    jsnfile = 'items.json'
    
    class ListSample(object):
        @cherrypy.expose
        def index(self):
            emps = []
            with open(jsnfile) as emp:
                emps = json.load(emp)
            templenv = Environment(loader=FileSystemLoader(os.getcwd()))
            return templenv.get_template('listitems.html').render(emps=emps)
    
    
    if __name__ == '__main__':
        cherrypy.quickstart(ListSample())
    
  • Running this sample

    From command prompt, navigate to code folder and execute command py list.py or python list.py
    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 to see the list of items.

Absolute Code Works - Python Topics