Table of contents
1.
Introduction
2.
Sample Program
3.
Frequently Asked Questions
3.1.
What is the distinction between an application and an application server?
3.2.
Define a multithreaded application server.
3.3.
What is the Kid template?
4.
Conclusion 
Last Updated: Mar 27, 2024

Javascript, CSS and Images in Cherrypy

Author Pradeep Kumar
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Hello readers! We hope you are doing well.

In this article, we will look at how to add static content to a cherrypy website. Static material, such as javascript, CSS files, and images, is one of the essential components of a website which makes it look beautiful. CherryPy supports serving static content to end users. 

In the next section, we will see go through a sample program to see how we can use static content in CherryPy.

Sample Program

In this example, we will create a webpage which generates a random natural number given the upper limit. We will also give it a background colour of "WhiteSmoke" to give the UI a rich feel. To do so, create a CSS file "style.css" inside the directory "public/css" and add the following piece of code:

body {
    background-color: whitesmoke;
}

Now, we will create a webpage where you can add a natural number as an upper limit, and upon pressing the Submit button, you get a random natural number less than or equal to that upper limit number. To do so, create a new file named main.py and add the following piece of code:

import os, os.path
import random
import cherrypy

class NumberGenerator(object):
    @cherrypy.expose
    def index(self):
        return """<html>
          <head>
            <link href="/static/css/style.css" rel="stylesheet">
          </head>
          <body>
            <form method="get" action="generate">
                <input type="text" value="10" name="upperlimit" />
                <button type="submit">Submit</button>
            </form>
          </body>
        </html>"""

    @cherrypy.expose
    def generate(self, upperlimit="10"):
        upperlimit = int(upperlimit)
        num = random.randint(1, upperlimit)
        cherrypy.session['myNum'] = str(num)
        return str(num)

    @cherrypy.expose
    def display(self):
        return cherrypy.session['myNum']

if __name__ == '__main__':
    conf = {
        '/': {
            'tools.sessions.on': True,
            'tools.staticdir.root': os.path.abspath(os.getcwd())
        },
        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': './public'
        }
    }
    cherrypy.quickstart(NumberGenerator(), '/', conf)

Now run the above program using the command python main.py and head over "http://localhost:8080/" to see the web page. Enter a valid integer and hit the submit button to see a random natural number that is less than or equal to the supplied value.

Output:

Before pressing the Submit button:

Image showing output before pressing the submit button

After Pressing the Submit button:

Image showing output upon pressing the submit button

CherryPy allows you to serve a single file or an entire directory structure. This is what you'll wind up doing most of the time, therefore, the code above displays it. First, we specify the location of all of our static stuff. For security reasons, this must be an absolute path. CherryPy will complain if you only supply relative routes while seeking a match to your URLs.

Then we specify that all URLs with path segments beginning with /static will be served with static content. That URL is mapped to the public directory, which is a direct child of the root directory. The full public directory subtree will be supplied as static content. CherryPy will map URLs to the paths included within that directory. As a result, /static/css/style.css can be accessed in public/css/style.css.

You can compile with the help of Online Javascript Compiler for better understanding.

Frequently Asked Questions

What is the distinction between an application and an application server?

An application is a piece of software which gathers information and an application server is a component holding one or more applications.

Define a multithreaded application server.

CherryPy offers a multithreaded environment for getting and setting values in the CherryPy namespace.

What is the Kid template?

The Kid is a straightforward template engine built in Python. Kid produces a Python module while constructing the template for the first time, which serves as a cached version of the template. In the kid template, the name of the template to be processed is necessary.

Conclusion 

In this article, we have extensively discussed adding Javascript, CSS, and images to a cherrypy website. We hope that this blog has helped you enhance your knowledge. To learn more,  check out the awesome content on the Coding Ninjas Website, Android DevelopmentCoding Ninjas Studio ProblemsCoding Ninjas Studio Interview BundleCoding Ninjas Studio Interview ExperiencesCoding Ninjas CoursesCoding Ninjas Studio Contests, and Coding Ninjas Studio Test Series

Do upvote our blog to help other ninjas grow. Happy Coding!

Thank you Image

Live masterclass