Python CGI Programming
What is CGI
CGI is currently maintained by NCSA, which defines CGI as follows:
CGI (Common Gateway Interface) is a program running on a server such as an HTTP server, providing an interface with the client's HTML pages.
Web browsing
To better understand how CGI works, we can follow the flow of clicking a link or URL on a web page:
- 1. Use your browser to access a URL and connect to the HTTP web server.
- 2. After receiving the request, the web server parses the URL and checks whether the requested file exists on the server. If it exists, the file contents are returned; otherwise, an error message is returned.
- 3. The browser receives the information from the server and displays the received file or the error message.
A CGI program can be a Python script, PERL script, SHELL script, C or C++ program, and so on.
CGI architecture diagram

Web server support and configuration
Before you start CGI programming, make sure your web server supports CGI and has a CGI handler configured.
Apache CGI support configuration:
Set up the CGI directory:
ScriptAlias /cgi-bin/ /var/www/cgi-bin/
All HTTP servers store CGI programs in a preconfigured directory. This directory is called the CGI directory and, by convention, is named /var/www/cgi-bin.
CGI files use the .cgi extension; Python can also use the .py extension.
By default, the cgi-bin directory on Linux servers is configured under /var/www.
If you want to specify another directory for running CGI scripts, modify the httpd.conf configuration file as shown below:
AllowOverride None
Options +ExecCGI
Order allow,deny
Allow from all
Add the .py suffix to AddHandler so that we can access Python script files ending in .py:
AddHandler cgi-script .cgi .pl .py
The first CGI program
We use Python to create the first CGI program, with the file name hello.py, located in the /var/www/cgi-bin directory, with the following contents:
Example
#!/usr/bin/python3
(
"Content-type:text/html"
)
(
)
A blank line telling the server the headers are finished
(
''
)
(
''
)
(
' '
)
(
'
)
(
''
)
(
''
)
(
'
Hello Word! I am the first CGI program from Runoob Tutorial
')
(
''
)
(
''
)
After saving the file, modify hello.py and set its file permissions to 755:
chmod 755 hello.py
Accessing the program above in a browser displays the following:

This hello.py script is a simple Python script. The first line of output, "Content-type:text/html", is sent to the browser to tell it that the displayed content type is "text/html".
A blank line is printed with print to tell the server that the header information is finished.
HTTP headers
The "Content-type:text/html" in the hello.py file is part of the HTTP header, which is sent to the browser to tell it the content type of the file.
The HTTP header format is as follows:
HTTP 字段名: 字段内容
For example:
Content-type: text/html
The following table describes HTTP header information commonly used in CGI programs:
| Header | Description |
|---|---|
| Content-type: | The MIME information corresponding to the entity in the request. For example: Content-type:text/html |
| Expires: Date | The date and time when the response expires |
| Location: URL | Used to redirect the recipient to a location other than the requested URL to complete the request or identify a new resource |
| Last-modified: Date | The last modification time of the requested resource |
| Content-length: N | The content length of the request |
| Set-Cookie: String | Set an HTTP Cookie |
CGI Environment Variables
All CGI programs receive the following environment variables, which play an important role in CGI programs:
| Variable Name | Description |
|---|---|
| CONTENT_TYPE | The value of this environment variable indicates the MIME type of the information being passed. Currently CONTENT_TYPE is generally application/x-www-form-urlencoded, indicating that the data comes from an HTML form. |
| CONTENT_LENGTH | When the server communicates with the CGI program via POST, this environment variable indicates the number of valid data bytes that can be read from standard input (STDIN); it must be used when reading input data. |
| HTTP_COOKIE | The COOKIE contents on the client. |
| HTTP_USER_AGENT | Provides client browser information including the version number or other proprietary data. |
| PATH_INFO | The value of this environment variable is the additional path information immediately following the CGI program name. It often appears as a parameter of the CGI program. |
| QUERY_STRING | If the server passes information to the CGI program using GET, the value of this environment variable is the information being passed. It follows the CGI program name, separated by a question mark '?'. |
| REMOTE_ADDR | The value of this environment variable is the IP address of the client sending the request, such as 192.168.1.67 above. This value is always present, and it is the only identifier the web client needs to provide to the web server, so it can be used in CGI programs to distinguish different web clients. |
| REMOTE_HOST | The value of this environment variable contains the host name of the client sending the CGI request. If the lookup is not supported, this environment variable need not be defined. |
| REQUEST_METHOD | Provides the method by which the script was invoked. For scripts using the HTTP/1.0 protocol, only GET and POST are meaningful. |
| SCRIPT_FILENAME | The full path of the CGI script |
| SCRIPT_NAME | The name of the CGI script |
| SERVER_NAME | This is the host name, alias, or IP address of your WEB server. |
| SERVER_SOFTWARE | The value of this environment variable contains the name and version of the HTTP server invoking the CGI program. For example, the value above is Apache/2.2.14(Unix) |
Below is a simple CGI script that outputs the CGI environment variables:
Example
#!/usr/bin/python3
import
os
(
"Content-type: text/html"
)
(
)
(
""
)
(
"Environment Variables
"
)
(
"
-
"
- %30s : %s "
)
for
key
in
os
.
environ
.
keys
(
)
:
(
"
%
(
key
,
os
.
environ
[
key
]
)
)
(
"
)
Save the above as test.py and change its file permissions to 755; the result is as follows:

GET and POST methods
Browser clients pass information to the server in two ways: the GET method and the POST method.
Transferring data with the GET method
The GET method sends encoded user information to the server; the data is included in the URL of the requested page, separated by a "?" as shown below:
http://www.test.com/cgi-bin/hello.py?key1=value1&key2=value2
Some other notes about GET requests:
- GET requests can be cached
- GET requests remain in the browser history
- GET requests can be bookmarked
- GET requests should not be used when handling sensitive data
- GET requests have a length limit
- GET requests should only be used to retrieve data
Simple URL example: GET method
Below is a simple URL that uses the GET method to send two parameters to the hello_get.py program:
/cgi-bin/hello_get.py?name=Runoob Tutorial&url=http://www.runoob.com
The code of the hello_get.py file is as follows:
Example
#!/usr/bin/python3
CGI processing module
import
cgi
,
cgitb
Create a FieldStorage instance
form
=
cgi
.
FieldStorage
(
)
Get the data
site_name
=
form.
getvalue
(
'name'
)
site_url
=
form.
getvalue
(
'url'
)
(
"Content-type:text/html"
)
(
)
(
""
)
(
""
)
(
""
)
(
"
)
(
""
)
(
""
)
(
"
%s official site: %s
"%
(
site_name
,
site_url
)
)
(
""
)
(
""
)
After saving the file, modify hello_get.py and set its file permissions to 755:
chmod 755 hello_get.py
The browser request produces the following output:

Simple form example: GET method
Below is an HTML form that uses the GET method to send two pieces of data to the server; the server script submitted to is again hello_get.py. The hello_get.html code is as follows:
Example
Runoob Tutorial(runoob.com)
By default the cgi-bin directory can only hold script files, so we store hello_get.html in the test directory and set its file permissions to 755:
chmod 755 hello_get.html
The GIF demonstration is shown below:

Passing data with the POST method
Using the POST method to pass data to the server is safer and more reliable; sensitive information such as user passwords should be sent with POST.
Below is again hello_get.py, which can also handle POST form data submitted by the browser:
Example
#!/usr/bin/python3
CGI processing module
import
cgi
,
cgitb
Create a FieldStorage instance
form
=
cgi
.
FieldStorage
(
)
Get the data
site_name
=
form.
getvalue
(
'name'
)
site_url
=
form.
getvalue
(
'url'
)
(
"Content-type:text/html"
)
(
)
(
""
)
(
""
)
(
""
)
(
"
)
(
""
)
(
""
)
(
"
%s official site: %s
"%
(
site_name
,
site_url
)
)
(
""
)
(
""
)
Below is a form submitting data via the POST method (method="post") to the server script hello_get.py:
Example
Runoob Tutorial(runoob.com)
The GIF demonstration is shown below:

Passing checkbox data through a CGI program
A checkbox submits one or more option values; the HTML code is as follows:
Example
Runoob Tutorial(runoob.com)
The code of the checkbox.py file is as follows:
Example
#!/usr/bin/python3
Import the CGI processing module
import
cgi
,
cgitb
Create a FieldStorage instance
form
=
cgi
.
FieldStorage
(
)
Receive the field data
if
form.
getvalue
(
'google'
)
:
google_flag
=
"Yes"
else
:
google_flag
=
"No"
if
form.
getvalue
(
'runoob'
)
:
runoob_flag
=
"Yes"
else
:
runoob_flag
=
"No"
(
"Content-type:text/html"
)
(
)
(
""
)
(
""
)
(
""
)
(
"
)
(
""
)
(
""
)
(
"
Is Runoob Tutorial selected: %s
"% runoob_flag
)
(
"
Is Google selected: %s
"% google_flag
)
(
""
)
(
""
)
Change the permissions of checkbox.py:
chmod 755 checkbox.py
GIF demonstration of browser access:

Passing radio data through a CGI program
A radio button passes only one value to the server; the HTML code is as follows:
Example
Runoob Tutorial(runoob.com)
The radiobutton.py script code is as follows:
Example
#!/usr/bin/python3
Import the CGI processing module
import
cgi
,
cgitb
Create a FieldStorage instance
form
=
cgi
.
FieldStorage
(
)
Receive the field data
if
form.
getvalue
(
'site'
)
:
site
=
form.
getvalue
(
'site'
)
else
:
site
=
"The submitted data is empty"
(
"Content-type:text/html"
)
(
)
(
""
)
(
""
)
(
""
)
(
"
)
(
""
)
(
""
)
(
"
The selected website is %s
"%
site
)
(
""
)
(
""
)
Change the permissions of radiobutton.py:
chmod 755 radiobutton.py
GIF demonstration of browser access:

Passing textarea data through a CGI program
A textarea passes multi-line data to the server; the HTML code is as follows:
Example
Runoob Tutorial(runoob.com)
The textarea.py script code is as follows:
Example
#!/usr/bin/python3
Import the CGI processing module
import
cgi
,
cgitb
Create a FieldStorage instance
form
=
cgi
.
FieldStorage
(
)
Receive the field data
if
form.
getvalue
(
'textcontent'
)
:
text_content
=
form.
getvalue
(
'textcontent'
)
else
:
text_content
=
"No content"
(
"Content-type:text/html"
)
(
)
(
""
)
(
""
)
(
""
)
(
"
)
(
""
)
(
""
)
(
"
The entered content is: %s
"% text_content
)
(
""
)
(
""
)
Change the permissions of textarea.py:
chmod 755 textarea.py
GIF demonstration of browser access:

Passing dropdown data through a CGI program.
The HTML dropdown code is as follows:
Example
Runoob Tutorial(runoob.com)
The dropdown.py script code is as follows:
Example
#!/usr/bin/python3
Import the CGI processing module
import
cgi
,
cgitb
Create a FieldStorage instance
form
=
cgi
.
FieldStorage
(
)
Receive the field data
if
form.
getvalue
(
'dropdown'
)
:
dropdown_value
=
form.
getvalue
(
'dropdown'
)
else
:
dropdown_value
=
"No content"
(
"Content-type:text/html"
)
(
)
(
""
)
(
""
)
(
""
)
(
"
)
(
""
)
(
""
)
(
"
The selected option is: %s
"% dropdown_value
)
(
""
)
(
""
)
Change the permissions of dropdown.py:
chmod 755 dropdown.py
GIF demonstration of browser access:

Using cookies in CGI
A major drawback of the http protocol is that it does not identify users, which causes great inconvenience for programmers; the cookie feature was introduced to make up for this.
A cookie is data written to the client's hard disk through the client's browser while the client visits a script; when the client visits the script again, the data is retrieved, making identity determination possible. Cookies are often used for authentication.
Cookie syntax
http cookies are sent through http headers, before the file is transferred. The syntax of the Set-Cookie header is as follows:
Set-cookie:name=name;expires=date;path=path;domain=domain;secure
- name=name: The value of the cookie to set (name cannot use ";" and "," characters); when there are multiple name values, separate them with ";" , for example:name1=name1;name2=name2;name3=name3。
- expires=date: The cookie's expiry, in the format: expires="Wdy,DD-Mon-YYYY HH:MM:SS"
- **path=path: ** sets the paths the cookie applies to. If path is a directory, the cookie applies to all files and subdirectories under it, for example: path="/cgi-bin/"; if path is a file, the cookie applies only to that file, for example: path="/cgi-bin/cookie.cgi".
- domain=domain: The domain for which the cookie is valid, for example: domain="www.runoob.com"
- secure: If this flag is given, it means the cookie can only be transmitted over https servers using the SSL protocol.
- Cookies are received by setting the environment variable HTTP_COOKIE; CGI programs can retrieve cookie information by looking up this variable.
Setting cookies
Setting a cookie is very simple: the cookie is sent separately in the http header. The following example sets name and expires in a cookie:
Example
#!/usr/bin/python3
(
'Set-Cookie: name="Runoob Tutorial";expires=Wed, 28 Aug 2016 18:30:00 GMT'
)
(
'Content-Type: text/html'
)
(
)
(
"""
Cookie set OK!
""")
Save the code above as cookie_set.py and change the permissions of cookie_set.py:
chmod 755 cookie_set.py
The example above uses the Set-Cookie header to set cookie information, with optional attributes such as the expiration time Expires, domain Domain, and path Path. This information is set in "Content-type:text/html" before.
Retrieving cookie information
Retrieving cookie information is also very simple: cookie information is stored in the CGI environment variable HTTP_COOKIE, in the following format:
key1=value1;key2=value2;key3=value3....
Below is a simple CGI program that retrieves cookie information:
Example
#!/usr/bin/python3
Import the module
import
os
import
http.
cookies
(
"Content-type: text/html"
)
(
)
(
"""
Read the cookie information
""")
if
'HTTP_COOKIE'
in
os
.
environ
:
cookie_string
=
os
.
environ
.
get
(
'HTTP_COOKIE'
)
c
=
http.
cookies
.
SimpleCookie
(
)
c=Cookie.SimpleCookie()
c.
load
(
cookie_string
)
try
:
data
=
c
[
'name'
]
.
value
(
"cookie data: "
+data+
"
"
)
except
KeyError
:
(
"cookie is not set or has expired
"
)
(
"""
""")
Save the code above as cookie_get.py and change the permissions of cookie_get.py:
chmod 755 cookie_get.py
The GIF demonstration of the cookie setting above is shown below:

File Upload Example
A form for uploading files in HTML needs to set the enctype attribute to multipart/form-data, as shown in the code below:
Example
Runoob Tutorial(runoob.com)
The save_file.py script code is as follows:
Example
#!/usr/bin/python3
import
cgi
,
os
import
cgitb
;
cgitb
.
enable
(
)
form
=
cgi
.
FieldStorage
(
)
Get the file name
fileitem
=
form
[
'filename'
]
Check whether the file was uploaded
if
fileitem.
filename
:
Set the file path
fn
=
os
.
path
.
basename
(
fileitem.
filename
)
open
(
'/tmp/'
- fn
,
'wb'
)
.
write
(
fileitem.
file
.
read
(
)
)
message
=
'File "'
- fn +
'" uploaded successfully'
else
:
message
=
'The file was not uploaded'
(
"""\
Content-Type: text/html\n
%s
"""%
(
message
,
)
)
Save the code above as save_file.py and change the permissions of save_file.py:
chmod 755 save_file.py
The GIF demonstration of the cookie setting above is shown below:

If your system is Unix/Linux, you must replace the file separator; on Windows you only need to use the open() statement:
fn = os.path.basename(fileitem.filename.replace("\\", "/" ))
File download dialog
First we create a foo.txt file in the current directory for the program to download.
File downloads are implemented by setting HTTP header information; the code is as follows:
Example
#!/usr/bin/python3
HTTP headers
(
"Content-Disposition: attachment; filename="foo.txt""
)
(
)
Opening a File
fo
=
open
(
"foo.txt"
,
"rb"
)
str
=
fo.
read
(
)
;
(
str
)
Closing a File
fo.
close
(
)