Many studies have determined that badly designed websites are often not read, trusted or visited for any length of time. "Poor interface design was particularly associated with rapid rejection and mistrust of a website," the study states, "In cases where the participants did not like some aspect of the design the site was often not explored further than the homepage and was not considered suitable for revisiting at a later date...". So, it is now obvious that decorating our CherryPy application is important as it will help give a good first expression to users.
The most basic tool for decorating a web application is CSS. So, now we will see how to decorate our application using CSS.
We will write an application where '<application-name>' opens the main page of our application. As the popularity of 'Dark Mode' is growing, we will also try to make our application in dark mode. For this we will link a stylesheet to our html code which the index method is returning.
First, create a 'style.css' file in the directory path 'public/css' and save it with the following code in it.
body {
color: white;
background-color: rgb(31, 44, 44);
}
Now, we will attach this .css file to our application. Save the below code in a file named 'css_app.py'.
import cherrypy
import os
class application:
def index(self):
return """<html>
<head>
<link href="/static/css/style.css" rel="stylesheet">
</head>
<body>
<p>We can design our application using CSS.</p>
</body>
</html>"""
if __name__ == '__main__':
conf = {
'/': {
'tools.staticdir.root': os.getcwd()
},
'/static': {
'tools.staticdir.on': True,
'tools.staticdir.dir': 'public'
}
}
cherrypy.quickstart(application(), '/', conf)
Here we can see the methods and the corresponding return values.
Notice that the return value of the index method is simply a HTML code with 'style.css' attached to it.
Also notice that the configurations of our application are changed. CherryPy provides support to serve a single file or a complete directory structure. First, we indicate the 'root' directory of all of our static content. This must be an absolute path. We have set this path using 'os.getcwd()' which returns the current working directory of the Python script.
Then we indicate that all URLs which the path segment starts with '/static' will be served as static content. We map that URL to the 'public' directory, a direct child of the 'root' directory. The entire subtree of the 'public' directory will be served as static content. CherryPy will map URLs to paths within that directory. This is why '/static/css/style.css' is found in 'public/css/style.css'.
Run the code through the Terminal/Command Line as follows:
python3 css_app.py
Now, if we enter http://localhost:8080/ in the address bar of a browser, the output will be something like this
We can change the 'color' and 'background-color' attributes in our .css file to better design our application.
Comments