Interview Questions

The classical "Hello World" in python CGI fashion:

Python Questions and Answers


(Continued from previous question...)

The classical "Hello World" in python CGI fashion:

#!/usr/bin/env python
print "Content-Type: text/html"
print
print """\
<html>
<body>
<h2>Hello World!
</body>
</html>
"""

To test your setup save it with the .py extension, upload it to your server as text and make it executable before trying to run it.

The first line of a python CGI script sets the path where the python interpreter will be found in the server. Ask your provider what is the correct one. If it is wrong the script will fail. Some examples:

#!/usr/bin/python
#!/usr/bin/python2.3
#!/usr/bin/python2.4

It is necessary that the script outputs the HTTP header. The HTTP header consists of one or more messages followed by a blank line. If the output of the script is to be interpreted as HTML then the content type will be text/html. The blank line signals the end of the header and is required.

print "Content-Type: text/html"
print

If you change the content type to text/plain the browser will not interpret the script's output as HTML but as pure text and you will only see the HTML source. Try it now to never forget. A page refresh may be necessary for it to work.

Client versus Server

All python code will be executed at the server only. The client's agent (for example the browser) will never see a single line of python. Instead it will only get the script's output. This is something realy important to understand.

When programming for the Web you are in a client-server environment, that is, do not make things like trying to open a file in the client's computer as if the script were running there. It isn't.

(Continued on next question...)

Other Interview Questions