9.1. Server Side Programming

Before Javascript, the only way to make your web application interactive and dynamic was to use forms and have a program that worked with your web server generate HTML on the fly. This is one of the most important ideas in web programming. We don’t have to limit our thinking about a web server returning the contents of a static file. It is all just text after all, so it does not have to come from a file, it could just as well be generated by a bunch of print statements in a program.

In fact that will be our starting point. All the other web development work since the mid 1990’s has been to improve upon the idea that a web page can be generated from some print statements.

Lets look at a hello world style example.

This should be pretty self explanatory. When you run this program it generates the text that looks just like the text you might find in a file named hello.html.

Now the next question is to ask how does this happen? How can I get this hello program to generate code and serve my own browser? The first thing you need to do is create a folder called www. In the www folder make a second folder called cgi-bin and place a hello.py file in that folder.

From the command line make sure that you are in the www folder and run the following command:

python3 -m http.server --cgi 8000

Then in your browser open the url: http://localhost:8000/cgi-bin/hello.py

When the web server sees a URL that is in the cgi-bin folder it knows that instead of just returning the contents of the file, it should execute the program and direct the output from that program back to the browser. Cool right?!

The program can be as complicated as you want, as long as the output of the program comprises html that constitutes a complete web page.

Note:

If the browser displays an error instead of the print() output, this might probably be either of the following:

Error code 403.
Message: CGI script is not executable ('/cgi-bin/hello.py').
Error code explanation: 403 = Request forbidden -- authorization will not help.

Move into the cgi-bin directory and type (for UNIX systems):

chmod a+x hello.py

This will make the hello.py script executable and allow the server to run it.

Or, you might get another error:

OSError: [Errno 8] Exec format error

This probably means that your default python executable is pointing to a different version of python than the program requires. Try to update the first line of the script to #!/usr/bin/python3 to point it to python 3.

Exercise: Write a program that calculates the first 25 fibonacci numbers and displays the output in a table.

You have attempted of activities on this page