Table of Contents
Hello Word! This is my first CGI program
Hello %s %s
CheckBox Maths is : %s
CheckBox Physics is : %s
 Selected Subject is %s
 Entered Text Content is %s
Home Backend Development Python Tutorial Python CGI programming

Python CGI programming

Nov 23, 2016 pm 02:05 PM

What is CGI

CGI is currently maintained by NCSA. NCSA defines CGI as follows:

CGI (Common Gateway Interface), common gateway interface, which is a program that runs on the server such as: HTTP server, providing the same client HTML page Interface.

Web browsing

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

1. Use your browser to access the URL and connect to the HTTP web server.

2. After receiving the request information, the web server will parse the URL and check whether the accessed file exists on the server. If the file exists, return the content of the file, otherwise an error message will be returned.

3. The browser receives information from the server and displays the received file or error message.

CGI programs can be Python scripts, PERL scripts, SHELL scripts, C or C++ programs, etc.

CGI Architecture Diagram

Python CGI programming

Web Server Support and Configuration

Before you perform CGI programming, make sure that your Web server supports CGI and has configured a CGI handler.

All HTTP server execution CGI programs are saved 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 where the Linux server is configured to run is /var/www.

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

AllowOverride None

Options ExecCGI

Order allow,deny

Allow from all

Options All

Directory>

The first CGI program

We use Python to create the first CGI program. The file name is hellp.py. The file is located in the /var/www/cgi-bin directory. The content is as follows. Modify the file The permissions are 755:

#!/usr/bin/python

print "Content-type: text/htmlrnrn"

print ''

print '

'

print '

Hello Word - First CGI Program'

print ''

print '

'

print '

Hello Word! This is my first CGI program

'

print

Hello Word! This is my first CGI program

This hello.py script is a simple Python script. The first output content of the script "Content-type: text/htmlrnrn" is sent to the browser And tell the browser that the displayed content type is "text/html".

HTTP header

hello.py file content "Content-type: text/htmlrnrn" is part of the HTTP header, which will be sent to the browser to tell the browser the content type of the file.

The format of the HTTP header is as follows:

HTTP field name: Field content

For example

Content-type: text/htmlrnrn

The following table introduces HTTP in CGI programs head Commonly used information:

Header

Description

Content-type: The requested MIME information corresponding to the entity. For example: Content-type:text/html

Expires: Date The date and time the response expires

Location: URL Used to redirect the recipient to the location of the non-requested URL to complete the request or identify a new resource

Last-modified : Date Last modification time of the requested resource

Content-length: N Requested content length

Set-Cookie: String Set Http Cookie

CGI environment variables

All CGI programs receive the following environment variables, these variables are in Played an important role in CGI programs:

Variable name

Description

CONTENT_TYPE The value of this environment variable indicates the MIME type of the information passed. Currently, the environment variable CONTENT_TYPE is generally: application/x-www-form-urlencoded, which indicates that the data comes from HTML forms.

CONTENT_LENGTH If the information transmission method between the server and the CGI program is POST, this environment variable is the number of bytes of valid data that can be read from the standard input STDIN. This environment variable must be used when reading the entered data.

HTTP_COOKIE The COOKIE content in the client.

HTTP_USER_AGENT Provides client browser information including version number or other proprietary data.

PATH_INFO The value of this environment variable represents other path information immediately after the CGI program name. It often appears as a parameter to CGI programs.

QUERY_STRING If the information transfer method between the server and the CGI program is GET, the value of this environment variable is the information transferred. This information 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 unique identifier that the Web client needs to provide to the Web server, which 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 that sent the CGI request. If the query you want to query is not supported, there is no need to define this environment variable.

REQUEST_METHOD Provides the method by which the script is called. 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 number of the HTTP server that calls the CGI program. For example, the above value is Apache/2.2.14 (Unix)

The following is a simple CGI script that outputs CGI environment variables:

#!/usr/bin/python

import os

print "Content-type: text/htmlrnrn";

print "Environment
";

for param in os.environ.keys():

print "%20s: %s
" % (param, os.environ[param])

GET and POST methods

The browser client passes two There are two ways to transmit information to the server, the two methods are the GET method and the POST method.

Use the GET method to transmit data

The GET method sends the encoded user information to the server. The data information is included in the URL of the request page, separated by "?", 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

GET request can be bookmarked in the history

GET request should not be used when handling sensitive data

GET request has a length limit

GET request should only be used to retrieve data

Simple url example: GET Method

The following is a simple URL that uses the GET method to send two parameters to the hello_get.py program:

/cgi-bin/hello_get.py?first_name=ZARA&last_name=ALI

The following Code for hello_get.py file:

#!/usr/bin/python

# CGI processing module

import cgi, cgitb

# Create an instantiation of FieldStorage

form = cgi.FieldStorage()

# Get data

first_name = form.getvalue('first_name')

last_name = form.getvalue('last_name')

print "Content-type: text/htmlrnrn"

print ""

print "

"

print "

Hello - Second CGI Program"

print ""

print "

"

print "

Hello %s %s

" % (first_name, last_name)

print ""

print ""

Browser request output result:

Hello ZARA ALI

Simple form example: GET method

The following is an HTML form that uses the GET method to send two data to the server. The submitted server script is also the hello_get.py file. The code is as follows:

First Name:

Last Name:

Use POST method to pass data

Use POST method Transmitting data to the server is more secure and reliable. Some sensitive information such as user passwords need to be transmitted using POST.

The following is also hello_get.py, which can also process POST form data submitted by the browser:

#!/usr/bin/python

# Introducing the CGI module

import cgi, cgitb

# Create FieldStorage instance

form = cgi.FieldStorage()

# Get form data

first_name = form.getvalue('first_name')

last_name = form.getvalue('last_name')

print "Content-type:text/htmlrnrn"

print ""

print "

"

print "

Hello - Second CGI Program"

print ""

print "

"

print "

Hello %s %s

" % (first_name, last_name)

print " "

print ""

The following form submits data to the server script hello_get.py through the POST method:

First Name:

Last Name:

Maths

Physics

The following is the code of the checkbox.cgi file:

#!/usr/bin/python

# Introduce CGI processing module

import cgi, cgitb

# Create an instance of FieldStorage

form = cgi.FieldStorage()

# Receive field data

if form.getvalue('maths' ):

math_flag = "ON"

else:

math_flag = "OFF"

if form.getvalue('physics'):

physics_flag = "ON"

else:

Physics_flag = " OFF"

print "Content-type:text/htmlrnrn"

print ""

print "

"

print "

Checkbox - Third CGI Program> ;"

print ""

print "

"

print "

CheckBox Maths is : %s

" % math_flag

print "

CheckBox Physics is : %s

" % physics_flag

print ""

print ""

Transfer Radio data through CGI program

Radio only to The server passes a data, the HTML code is as follows:

 Maths

 Physics

   

radiobutton.py 脚本代码如下:

#!/usr/bin/python

 

# Import modules for CGI handling 

import cgi, cgitb 

 

# Create instance of FieldStorage 

form = cgi.FieldStorage() 

 

# Get data from fields

if form.getvalue('subject'):

   subject = form.getvalue('subject')

else:

   subject = "Not set"

 

print "Content-type:text/htmlrnrn"

print ""

print "

"

print "

Radio - Fourth CGI Program"

print ""

print "

"

print "

 Selected Subject is %s

" % subject

print ""

print ""

   

通过CGI程序传递 Textarea 数据

Textarea向服务器传递多行数据,HTML代码如下:

Type your text here...

   

textarea.cgi脚本代码如下:

#!/usr/bin/python

 

# Import modules for CGI handling 

import cgi, cgitb 

 

# Create instance of FieldStorage 

form = cgi.FieldStorage() 

 

# Get data from fields

if form.getvalue('textcontent'):

   text_content = form.getvalue('textcontent')

else:

   text_content = "Not entered"

 

print "Content-type:text/htmlrnrn"

print ""

print "

";

print "

Text Area - Fifth CGI Program"

print ""

print "

"

print "

 Entered Text Content is %s

" % text_content

print ""

   

通过CGI程序传递下拉数据

HTML下拉框代码如下:

   

dropdown.py 脚本代码如下所示:

#!/usr/bin/python

 

# Import modules for CGI handling 

import cgi, cgitb 

 

# Create instance of FieldStorage 

form = cgi.FieldStorage() 

 

# Get data from fields

if form.getvalue('dropdown'):

   subject = form.getvalue('dropdown')

else:

   subject = "Not entered"

 

print "Content-type:text/htmlrnrn"

print ""

print "

"

print "

Dropdown Box - Sixth CGI Program"

print ""

print " & lt; body & gt; "

Print" & lt; h2 & gt; select subject is%s & lt;/h2 & gt; gt; "" ""

Cookies used in CGI

A big shortcoming of the http protocol is that it does not judge the user's identity, which brings great inconvenience to programmers.

The emergence of the cookie function makes up for this shortcoming.

All cookies are to write record data on the customer's hard drive through the customer's browser when the customer accesses the script. The data information will be retrieved the next time the customer accesses the script, thereby achieving the function of identity discrimination. Cookies are commonly used in Password is being determined.

 

Cookie syntax

http cookie is sent through the http header, which is earlier than the file transfer. The syntax of set-cookie in the header is as follows:

Set-cookie:name= name;expires=date;path=path;domain=domain;secure

name=name: You need to set the cookie value (name cannot use ";" and ","), when there are multiple name values Separate with ";" For example: name1=name1;name2=name2;name3=name3.

expires=date: The validity period of cookie, format: expires="Wdy,DD-Mon-YYYY HH:MM:SS"

path=path: Set the path supported by cookie, if path is a path, then Cookies are effective for all files and subdirectories in this directory, for example: path="/cgi-bin/". If path is a file, the cookie is effective for this file, for example: path="/cgi-bin/cookie" .cgi".

domain=domain: The domain name that is valid for the cookie, for example: domain="www.chinalb.com"

secure: If this flag is given, it means that the cookie can only be delivered through the https server of the SSL protocol.

The reception of cookies is achieved by setting the environment variable HTTP_COOKIE. CGI programs can obtain cookie information by retrieving this variable.

Cookie Settings

Cookie setting is very simple, the cookie will be sent separately in the http header. The following example sets UserID and Password in cookies:

<p></p>#!/usr/bin/python<p></p> <p></p>print "Set-Cookie:UserID=XYZ;rn"<p></p>print "Set-Cookie:Password=XYZ123;rn"<p></p>print "Set-Cookie:Expires=Tuesday, 31-Dec-2007 23:12:40 GMT";rn"<p></p>print "Set-Cookie:Domain=www. ziqiangxuetang.com;rn"<p></p>print "Set-Cookie:Path=/perl;n"<p></p>print "Content-type:text/htmlrnrn"<p></p>.....Rest of the HTML Content....<p></p> <p></p><p></p>The above example uses Set-Cookie header information to set Cookie information. Other attributes of Cookie are optionally set, such as expiration time Expires, domain name, and path. This information is set in. "Content-type: text/htmlrnrn". <p></p>Retrieve Cookie information<p></p>Cookie information retrieval page is very simple. Cookie information is stored in the CGI environment variable HTTP_COOKIE, and the storage format is as follows: <p></p><p></p><p></p>key1=value1; key2=value2;key3=value3....<p></p> <p></p><p></p>The following is a simple CGI program to retrieve cookie information: <p></p><p></p><p></p>#!/usr/bin/python<p></p> <p></p>#Import modules for CGI handling <p></p>from os import environ<p></p>import cgi, cgitb<p></p> <p></p>if environ.has_key('HTTP_COOKIE'):<p></p> for cookie in map(strip, split(environ['HTTP_COOKIE'], ';' )):<p></p> (key, value) = split(cookie, '=');<p></p> if key == "UserID":<p></p> user_id = value<p></p><p></p> if key == "Password" :<p></p>                  password = value<p></p><p></p>print "User ID = %s" % user_id<p></p>print "Password = %s" % password<p></p> <p></p><p></p>The output of the above script is as follows: <p></p><p></p><p></p>U ser ID = XYZ<p> DPassword = xyz123</p><p> File Upload example: </p><p>Html Set the form of upload file to set the enableype property as Multipart/Form-Data, the code is as shown below: </p><p></p><p></p><p> & lt; html & gt; </p><p> </p><p>                                          </p><p> </p><p><input type="submit" value="Upload"></p><p> </p><p></p> <p></p><p> </p><p></p><p>save_file.py script file code is as follows: </p><p></p><p></p><p>#!/usr/bin/python</p><p> </p><p>import cgi, os</p><p>import cgit b; cgitb.enable ()</p><p></p><p>form = cgi.FieldStorage()</p><p></p><p># Get the file name</p><p>fileitem = form['filename']</p><p></p><p># Check whether the file is uploaded</p><p>if fileitem.filename:</p> <p>  # Set file path </p><p> fn = os.path.basename(fileitem.filename) </p><p> open('/tmp/' + fn, 'wb').write(fileitem.file.read())</p><p> </p><p> message = 'The file "' + fn + '" was uploaded successfully'</p><p> </p><p>else:</p><p> message = 'No file was uploaded'</p><p>print """</p><p>Content-Type: text/htmln </p><p>&lt ;html></p><p></p><p> </p><p>%s</p><p></p><p></p><p>""" % (message,)</p><p> </p> <p></p> <p>If the system you are using is Unix/Linux, you must replace the file separator. Under window, you only need to use the open() statement: </p><p></p><p></p><p>fn = os.path.basename(fileitem.filename.replace ("\", "/" ))</p><p> </p><p></p><p>File download dialog box</p><p>If we need to provide the user with a file download link and pop up the file download dialog box after the user clicks the link, we set the HTTP header information To implement these functions, the function code is as follows: </p><p></p><p></p><p>#!/usr/bin/python</p><p></p><p># HTTP Header</p><p>print "Content-Type: application/octet-stream; name="FileName"rn ";</p><p>print "Content-Disposition: attachment; filename="FileName"rnn";</p><p></p><p># Actual File Content will go hear.</p><p>fo = open("foo.txt", "rb")</p><p> </p><p>str = fo.read();</p><p>print str</p><p></p><p>#Close opend file</p><p>fo.close()</p><p> </p><p></p><p></p><p></p>
Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1263
29
C# Tutorial
1237
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

How Much Python Can You Learn in 2 Hours? How Much Python Can You Learn in 2 Hours? Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

See all articles