Code Toolkit: Python, Fall 2021

Adding CSS to CGI output

A few times in class I have mentioned that you could integrate CSS into your CGI scripts to format the output generated by your Python CGI programs. A few people have asked me how to do this, so I thought that I would share my explanation with everyone.

I'll try my best to explain how to do this here with a simple example, but to make it work with your project, you will need to integrate it with whatever code you are working on.

Here is a bit of code across two files that you could use to implement this. This first snippet would go in your CGI script — i.e., the .py file in your cgi-bin directory.

#!/path/to/your/python3

print("Content-type: text/html")
print("")

html = """
<link rel='stylesheet' href='/css/styles.css'>
<div>
Hello, world
</div>
"""
print(html)

If you are trying to integrate this with existing code, you cannot simply copy/paste all of that as one chunk. You have to integrate it by interspersing it with the existing code that you are working with. Read on for more explanation.

Remember that the first line (the hash-bang line) must include the path to your python3. I've include something here merely as a placeholder. Use the hash-bang line that you already have working for you.

The second corresponding bit of code should go into a file called styles.css file that would need to go in a folder called css inside your project folder.

/* put this in a directory called css */

div {
  width: 500px;
  height: 500px;
  border: solid 1px #f00;
}

Here is a screenshot that illustrates how I have my project files arranged. It's important that you follow this precise organization.

(Click to enlarge.)

Remember that any files in your cgi-bin folder will need to be executable in order to be run as CGI scripts. So that means running chmod a+x server.py (and doing that for any .py CGI script that you wish to run). You do not need to do this for styles.css – nor for any CSS files.

Besides all that, the important thing to notice here is line 7 of server.py:

<link rel='stylesheet' href='/css/styles.css'>
This is what will link the HTML output of your .py CGI script to the .css file.

If you do this, then any CSS rules that you specify in css/styles.css should be applied to the HTML output generated by server.py

In my example, my server.py simply prints a simple <div> that includes the text "Hello world", and my styles.css file gives that a width, height, and border. This is the part that you will obviously need to adapt to whatever it is that you are working on.

The important thing is that when your CGI script is generating its output, the first bit of HTML that it generates should be the <link> line above. This must come after the "Content-type" line and the blank line that follows, and before any other HTML.

Good luck!