[siː dʒiː aɪ]
Note: if you can’t see the title, it means your browser can’t display Unicode characters properly.
The Common Gateway Interface (CGI) is a standard protocol for interfacing external application software with an information server, commonly a web server. This allows the server to pass requests from a client web browser to the external application. The web server can then return the output from the application to the web browser.
Today, I’ll explain how to generate Web pages using Python - the easiest programming language ever. They won’t be just static pages, however; in the article there will be examples of CGI scripts processing data from HTML forms, uploading files to the server, some GET and POST requests and even a simple how-to showing how to set up a small CGI server. However, this article is about using CGI in Python, so I assume you have some knowledge of the Python syntax.
The simpliest of the simpliest
Let’s start with a simple static page. The first line of any CGI script has to point to the location of Python. It’ll usually be /usr/bin/python on most Unix-based servers. Next, we have to inform Python that the output of the script is actually HTML (and put an \n at the end of this line)- and the rest of the code is up to you. Remember that all CGI scripts need permissions at least equal to chmod 755.
#!/usr/bin/python
print "Content-type: text/html\\n"
print "OMG, it's actually working!"
You can see the script working.
Of course, this script doesn’t even include the most basic html tags such as <html> and <body>, so have a look at a second example:
#!/usr/bin/python
print "Content-type: text/html\\n"
print """<html>
<head>
<title>OMG</title>
</head>
<body>
<h2>It's actually working!</h2>
<img src="some_crappy_image_source">
</body>
</html>"""
Again, you can see how it works.
