Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python CGI Programming

Python CGI Programming


What is CGI

CGI is currently maintained by NCSA, which defines CGI as follows:

CGI (Common Gateway Interface) is a program that runs on a server such as an HTTP server and provides an interface with client HTML pages.

Note:

Since Python 3.11, the cgi module has been officially marked as deprecated, and it was removed starting from Python 3.13.

It is recommended to migrate to Flask, Django or FastAPI and other modern web frameworks.


Web browsing

To better understand how CGI works, we can look at the process of clicking a link or URL on a web page:

A CGI program can be a Python script, a PERL script, a SHELL script, a C or C++ program, and so on.


CGI architecture diagram

cgiarch


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 pre-configured directory. This directory is called the CGI directory, and by convention it is named /var/www/cgi-bin.

The extension of CGI files is .cgi, and Python can also use the .py extension.

By default, the cgi-bin directory configured to run on a Linux server is /var/www.

If you want to specify another directory for running CGI scripts, you can modify the httpd.conf configuration file as follows:


   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 our first CGI program in a file named hello.py located in the /var/www/cgi-bin directory, with the following content:


#!/usr/bin/python
# -*- coding: UTF-8 -*-

print "Content-type:text/html"
print                               # 空行,告诉服务器结束头部
print ''
print ''
print ''
print 'Hello World - 我的第一个 CGI 程序!'
print ''
print ''
print '

Hello World! 我是来自Runoob Tutorial的第一CGI程序

' print '' print ''

After saving the file, modify hello.py and set its file permissions to 755:

chmod 755 hello.py 

Access the above program in a browser at http://localhost/cgi-bin/hello.py The display result is as follows:


Hello World! 我是来自Runoob Tutorial的第一CGI程序

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 If the server passes information to the CGI program using POST, this environment variable is the number of bytes of valid data that can be read from standard input STDIN. This environment variable must be used when reading the 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 passed. This information follows the CGI program name, separated from it 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:


#!/usr/bin/python
# -*- coding: UTF-8 -*-
# filename:test.py

import os

print "Content-type: text/html"
print
print ""
print "环境变量
"; print "
    " for key in os.environ.keys(): print "
  • %30s : %s
  • " % (key,os.environ[key]) print "
"

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:

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/test.py?name=Runoob Tutorial&url=http://www.runoob.com

The following is the code of the hello_get.py file:


#!/usr/bin/python
# -*- coding: UTF-8 -*-

# filename:test.py

# CGI processing module
import cgi, cgitb 

# Create an instance of FieldStorage
form = cgi.FieldStorage() 

# Get data
site_name = form.getvalue('name')
site_url  = form.getvalue('url')

print "Content-type:text/html"
print
print ""
print ""
print ""
print "Runoob Tutorial CGI 测试实例"
print ""
print ""
print "

%s官网:%s

" % (site_name, site_url) print "" print ""

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:






Runoob Tutorial(runoob.com)


站点名称:
站点 URL:

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:


#!/usr/bin/python
# -*- coding: UTF-8 -*-

# CGI processing module
import cgi, cgitb 

# Create an instance of FieldStorage
form = cgi.FieldStorage() 

# Get data
site_name = form.getvalue('name')
site_url  = form.getvalue('url')

print "Content-type:text/html"
print
print ""
print ""
print ""
print "Runoob Tutorial CGI 测试实例"
print ""
print ""
print "

%s官网:%s

" % (site_name, site_url) print "" print ""

Below is a form submitting data via the POST method (method="post") to the server script hello_get.py:






Runoob Tutorial(runoob.com)


站点名称:
站点 URL:

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:






Runoob Tutorial(runoob.com)


Runoob Tutorial Google

The code of the checkbox.py file is as follows:


#!/usr/bin/python
# -*- coding: UTF-8 -*-

# Import CGI processing module
import cgi, cgitb 

# Create an instance of FieldStorage
form = cgi.FieldStorage() 

# Receive field data
if form.getvalue('google'):
   google_flag = "是"
else:
   google_flag = "否"

if form.getvalue('runoob'):
   runoob_flag = "是"
else:
   runoob_flag = "否"

print "Content-type:text/html"
print
print ""
print ""
print ""
print "Runoob Tutorial CGI 测试实例"
print ""
print ""
print "

Runoob Tutorial是否选择了 : %s

" % runoob_flag print "

Google 是否选择了 : %s

" % google_flag print "" print ""

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:






Runoob Tutorial(runoob.com)


Runoob Tutorial Google

The radiobutton.py script code is as follows:


#!/usr/bin/python
# -*- coding: UTF-8 -*-

# Import CGI processing module
import cgi, cgitb 

# Create an instance of FieldStorage
form = cgi.FieldStorage() 

# Receive field data
if form.getvalue('site'):
   site = form.getvalue('site')
else:
   site = "提交数据为空"

print "Content-type:text/html"
print
print ""
print ""
print ""
print "Runoob Tutorial CGI 测试实例"
print ""
print ""
print "

选中的网站是 %s

" % site print "" print ""

Change the permissions of radiobutton.py:


chmod 755 radiobutton.py

GIF demonstration of browser access:

Passing textarea data through a CGI program

Textarea passes multi-line data to the server. The HTML code is as follows:






Runoob Tutorial(runoob.com)


The textarea.py script code is as follows:


#!/usr/bin/python
# -*- coding: UTF-8 -*-

# Import CGI processing module
import cgi, cgitb 

# Create an instance of FieldStorage
form = cgi.FieldStorage() 

# Receive field data
if form.getvalue('textcontent'):
   text_content = form.getvalue('textcontent')
else:
   text_content = "没有内容"

print "Content-type:text/html"
print
print ""
print "";
print ""
print "Runoob Tutorial CGI 测试实例"
print ""
print ""
print "

输入的内容是:%s

" % text_content print "" print ""

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:






Runoob Tutorial(runoob.com)


The dropdown.py script code is as follows:


#!/usr/bin/python
# -*- coding: UTF-8 -*-

# Import CGI processing module
import cgi, cgitb 

# Create an instance of FieldStorage
form = cgi.FieldStorage() 

# Receive field data
if form.getvalue('dropdown'):
   dropdown_value = form.getvalue('dropdown')
else:
   dropdown_value = "没有内容"

print "Content-type:text/html"
print
print ""
print ""
print ""
print "Runoob Tutorial CGI 测试实例"
print ""
print ""
print "

选中的选项是:%s

" % dropdown_value print "" print ""

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 

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:


#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 
print 'Content-Type: text/html'
print 'Set-Cookie: name="Runoob Tutorial";expires=Wed, 28 Aug 2016 18:30:00 GMT'
print
print """

    
        
        Runoob Tutorial(runoob.com)
    
    
        

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 above example uses the Set-Cookie header to set cookie information, with optional attributes such as expiration time Expires, domain Domain, and path Path. This information is set before "Content-type:text/html".


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:


#!/usr/bin/python
# -*- coding: UTF-8 -*-

# Import module
import os
import Cookie

print "Content-type: text/html"
print

print """



Runoob Tutorial(runoob.com)


读取cookie信息

""" if 'HTTP_COOKIE' in os.environ: cookie_string=os.environ.get('HTTP_COOKIE') c=Cookie.SimpleCookie() c.load(cookie_string) try: data=c['name'].value print "cookie data: "+data+"
" except KeyError: print "cookie 没有设置或者已过期
" print """ """

Save the code above as cookie_get.py and change the permissions of cookie_get.py:


chmod 755 cookie_get.py

The above cookie sets the color Gif as follows:

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:






Runoob Tutorial(runoob.com)


 

选中文件:

The code of the save_file.py script file is as follows:


#!/usr/bin/python
# -*- coding: UTF-8 -*-

import cgi, os
import cgitb; cgitb.enable()

form = cgi.FieldStorage()

# Get filename
fileitem = form['filename']

# Check if file is uploaded
if fileitem.filename:
   # Set file path
   fn = os.path.basename(fileitem.filename)
   open('/tmp/' + fn, 'wb').write(fileitem.file.read())

   message = '文件 "' + fn + '" 上传成功'
   
else:
   message = '文件没有上传'
   
print """\
Content-Type: text/html\n



Runoob Tutorial(runoob.com)


   

%s

""" % (message,)

Save the code above as save_file.py and change the permissions of save_file.py:


chmod 755 save_file.py

The above cookie sets the color Gif as follows:

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:


#!/usr/bin/python
# -*- coding: UTF-8 -*-

# HTTP 头部
print "Content-Disposition: attachment; filename=\"foo.txt\"";
print
# Open file
fo = open("foo.txt", "rb")

str = fo.read();
print str

# Close file
fo.close()