Python CGI Programming

Source: Internet
Author: User
Tags http cookie

What is CGI

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

CGI (Common Gateway Interface), a universal Gateway interface, is a program that runs on a server such as an HTTP server, providing an interface with the client HTML page.

Web browsing

To get a better idea of how CGI works, we can click on a link or URL from the Web page:

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

2. When the Web server receives the request information, it resolves the URL and finds whether the file accessed exists on the server and returns an error message if there is the contents of the returned file.

3. The browser receives the 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, and so on.

CGI Frame composition

Web server support and configuration

Before you perform CGI programming, make sure that your Web server supports CGI and a CGI-configured 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 the/var/www/cgi-bin directory.

CGI files with the. cgi,python extension can also use the. py extension.

By default, the Linux server configuration runs in the Cgi-bin directory as/var/www.

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

<directory "/var/www/cgi-bin" >

AllowOverride None

Options execcgi

Order Allow,deny

Allow from all

</Directory>

<directory "/var/www/cgi-bin" >

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 in the/var/www/cgi-bin directory, the content is as follows, the permission to modify the file is 755:

#!/usr/bin/python

Print "content-type:text/html\r\n\r\n"

print '

print '

print ' <title>hello word-first CGI program</title> '

print '

print ' <body> '

print '

print ' </body> '

print '

The above program in the browser access displays the results as follows:

Hello word! This is my first CGI program

This hello.py script is a simple Python script where the first output of the script "content-type:text/html\r\n\r\n" is sent to the browser and tells the browser that the content type shown is "text/html".

HTTP Header

The "content-type:text/html\r\n\r\n" in the contents of the hello.py file is part of the HTTP header, which is sent to the browser to tell the browser the content type of the file.

The HTTP header format is as follows:

HTTP Field Name: Field contents

For example

content-type:text/html\r\n\r\n

The following table describes the frequently used information in the HTTP header in CGI programs:

Head

Describe

Content-type: The requested MIME information that corresponds to the entity. Example: content-type:text/html

Expires:date the date and time the response expires

The Location:url is used to redirect the receiver to the location of the non-request URL to complete the request or identify the new resource

Last-modified:date last modified time to request resources

Content-length:n the requested content length

Set-cookie:string Setting HTTP Cookies

CGI Environment variables

All CGI programs receive the following environment variables, which play an important role in CGI programs:

Variable name

Describe

Content_Type the value of this environment variable indicates the MIME type of the information being passed. Currently, the environment variable content_type is generally: application/x-www-form-urlencoded, who says the data comes from an HTML form.

Content_length if the server and CGI program information is passed as 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 input data.

Http_cookie the COOKIE content within the client.

Http_user_agent provides customer browser information that contains a version number or other proprietary data.

Path_info the value of this environment variable represents the other path information immediately following the CGI program name. It often appears as a parameter to a CGI program.

Query_string if the server and CGI program information is passed in a get, the value of this environment variable even if the information is passed. This information is followed by the CGI program name, with a question mark '? ' in between. Separated.

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 a unique identifier that Web clients need to provide to the Web server, which can be used in a CGI program to differentiate between different Web clients.

Remote_host the value of this environment variable contains the host name of the client that sent the CGI request. If you do not support the query, you do not need to define this environment variable.

Request_method provides the method that the script is called. For scripts that use the http/1.0 protocol, only get and POST make sense.

Full path to the Script_filename 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 called the CGI program. For example, the value above 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/html\r\n\r\n";

Print "<font size=+1>environment</font><\br>";

For Param in Os.environ.keys ():

Print "<B>%20S</B>:%s<\br>"% (param, Os.environ[param])

Get and Post methods

The browser client passes information to the server in two ways, both the GET method and the POST method.

Using the Get method to transfer data

The Get method sends the encoded user information to the server side, and the data information is included on the URL of the request page with "?". The number is divided as follows:

Http://www.test.com/cgi-bin/hello.py?key1=value1&key2=value2

Some additional comments about the GET request:

Get requests can be cached

GET requests remain in browser history

Get requests can be bookmark-Favorites

GET requests should not be used when handling sensitive data

Get request has a length limit

GET requests should only be used to retrieve data

Simple URL instance: Get method

Here is a simple URL that uses the Get method to send two parameters to a hello_get.py program:

/cgi-bin/hello_get.py?first_name=zara&last_name=ali

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

#!/usr/bin/python

# CGI Processing module

Import CGI, CGITB

# Create an instantiation of a fieldstorage

form = CGI. Fieldstorage ()

# Get Data

first_name = Form.getvalue (' first_name ')

last_name = Form.getvalue (' last_name ')

Print "content-type:text/html\r\n\r\n"

Print "

Print "

Print "<title>hello-second CGI program</title>"

Print "

Print "<body>"

Print "

Print "</body>"

Print "

Browser Request output:

Hello ZARA ALI

Simple Form instance: Get method

Here is an HTML-based form that uses the Get method to send two data to the server, and the submitted server script is also a hello_get.py file with the following code:

<form action= "/cgi-bin/hello_get.py" method= "Get" >

First Name: <input type= "text" name= "first_name" > <br/>

Last Name: <input type= "text" name= "last_name"/>

<input type= "Submit" value= "Submit"/>

</form>

Passing data using the Post method

Using the Post method to pass data to the server is more secure and reliable, such as sensitive information such as user passwords and the need to use post to transmit data.

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

#!/usr/bin/python

# Introduction of CGI Modules

Import CGI, CGITB

# Create Fieldstorage instances

form = CGI. Fieldstorage ()

# get form data

first_name = Form.getvalue (' first_name ')

last_name = Form.getvalue (' last_name ')

Print "content-type:text/html\r\n\r\n"

Print "

Print "

Print "<title>hello-second CGI program</title>"

Print "

Print "<body>"

Print "

Print "</body>"

Print "

Here is how the form submits data to the server script hello_get.py via the Post method:

<form action= "/cgi-bin/hello_get.py" method= "POST" >

First Name: <input type= "text" name= "first_name" ><br/>

Last Name: <input type= "text" name= "last_name"/>

<input type= "Submit" value= "Submit"/>

</form>

Passing checkbox data through a CGI program

The checkbox is used to submit one or more option data with the following HTML code:

<form action= "/cgi-bin/checkbox.cgi" method= "POST" target= "_blank" >

<input type= "checkbox" Name= "Maths" value= "on"/> Maths

<input type= "checkbox" Name= "Physics" value= "on"/> Physics

<input type= "Submit" value= "Select Subject"/>

</form>

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

#!/usr/bin/python

# Introduction of 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/html\r\n\r\n"

Print "

Print "

Print "<title>checkbox-third CGI program</title>"

Print "

Print "<body>"

Print "

Print "

Print "</body>"

Print "

Passing radio data through a CGI program

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

<form action= "/cgi-bin/radiobutton.py" method= "post" target= "_blank" >

<input type= "Radio" name= "subject" value= "maths"/> Maths

<input type= "Radio" name= "Subject" value= "Physics"/> Physics

<input type= "Submit" value= "Select Subject"/>

</form>

The radiobutton.py script code is as follows:

#!/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/html\r\n\r\n"

Print "

Print "

Print "<title>radio-fourth CGI program</title>"

Print "

Print "<body>"

Print "

Print "</body>"

Print "

Passing Textarea data through a CGI program

TextArea passes multiple lines of data to the server, with the following HTML code:

<form action= "/cgi-bin/textarea.py" method= "post" target= "_blank" >

<textarea name= "Textcontent" cols= "+" rows= "4" >

Type your text here ...

</textarea>

<input type= "Submit" value= "Submit"/>

</form>

The textarea.cgi script code is as follows:

#!/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/html\r\n\r\n"

Print "

print "

Print "<title>text area-fifth CGI program</title>"

Print "

Print "<body>"

Print "

Print "</body>"

Passing pull-down data through a CGI program

The HTML drop-down box code is as follows:

<form action= "/cgi-bin/dropdown.py" method= "post" target= "_blank" >

<select name= "Dropdown" >

<option value= "Maths" selected>maths</option>

<option value= "Physics" >Physics</option>

</select>

<input type= "Submit" value= "Submit"/>

</form>

The dropdown.py script code looks like this:

#!/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/html\r\n\r\n"

Print "

Print "

Print "<title>dropdown box-sixth CGI program</title>"

Print "

Print "<body>"

Print "

Print "</body>"

Print "

Using cookies in CGI

In the HTTP protocol a big drawback is not to make the user's identity judgment, so that the programmer to bring great inconvenience,

The advent of the cookie function compensates for this shortcoming.

All cookies are written on the client's hard drive through the client's browser while the client accesses the script, and when the next client accesses the script, it retrieves the data information, which is used in the password judgment.

 

The syntax of a cookie

HTTP cookie is sent through the HTTP header to achieve, he was earlier than the file transfer, the head Set-cookie syntax as follows:

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

Name=name: The value of the cookie needs to be set (name cannot use ";" and ","), with multiple name values separated by ";" For example: Name1=name1;name2=name2;name3=name3.

Expires=date:cookie expiration date, format: expires= "wdy,dd-mon-yyyy HH:MM:SS"

Path=path: Sets the path supported by the cookie, if path is a path, then the cookie takes effect for all files and subdirectories in this directory, for example: Path= "/cgi-bin/", if path is a file, the cookie means that the file is in effect, 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 passed through an HTTPS server on the SSL protocol.

The receipt of a cookie is implemented by setting the environment variable Http_cookie, which can be retrieved by the CGI program to obtain cookie information.

Cookie settings

Cookies are very simple to set up, and cookies are sent separately in the HTTP header. The following example sets the UserID and Password in the cookie:

<pre>

#!/usr/bin/python

Print "set-cookie:userid=xyz;\r\n"

Print "set-cookie:password=xyz123;\r\n"

Print "Set-cookie:expires=tuesday, 31-dec-2007 23:12:40 GMT"; \ r \ n "

Print "set-cookie:domain=www.ziqiangxuetang.com;\r\n"

Print "set-cookie:path=/perl;\n"

Print "content-type:text/html\r\n\r\n"

........... Rest of the HTML Content ....

The above example uses the Set-cookie header information to set the cookie information, optionally setting the other attributes of the cookie, such as expiration time expires, domain name, path. This information is set before "content-type:text/html\r\n\r\n".

Retrieving cookie Information

The Cookie Information retrieval page is very simple and the cookie information is stored in the CGI environment variable Http_cookie, which is stored in the following format:

Key1=value1;key2=value2;key3=value3 ....

The following is a simple CGI procedure for retrieving cookie information:

#!/usr/bin/python

# Import modules for CGI handling

From OS import environ

Import CGI, CGITB

If Environ.has_key (' Http_cookie '):

For cookies in map (strip, Split (environ[' Http_cookie '), '; ')):

(key, value) = Split (cookie, ' = ');

If key = = "UserID":

user_id = value

If key = = "Password":

Password = value

Print "User ID =%s"% user_id

Print "Password =%s"% Password

The above script output results are as follows:

User ID = XYZ

Password = XYZ123

File Upload instance:

HTML Settings The form of the upload file needs to be set enctype property to Multipart/form-data, as shown in the code below:

<body>

<form enctype= "Multipart/form-data"

action= "save_file.py" method= "POST" >

<p>file: <input type= "File" name= "filename"/></p>

<p><input type= "Submit" value= "Upload"/></p>

</form>

</body>

The save_file.py script file code is as follows:

#!/usr/bin/python

Import CGI, OS

Import CGITB; Cgitb.enable ()

form = CGI. Fieldstorage ()

# Get file name

Fileitem = form[' filename ']

# detect if files are uploaded

If Fileitem.filename:

# Set File path

fn = Os.path.basename (fileitem.filename)

Open ('/tmp/' + FN, ' WB '). Write (Fileitem.file.read ())

Message = ' The file ' ' + fn + ' was uploaded successfully '

Else

message = ' No file ' was uploaded '

print "" \

Content-type:text/html\n

<body>

<p>%s</p>

</body>

"" "% (message,)

If the system you are using is Unix/linux, you must replace the file delimiter, and only use the open () statement under window:

fn = Os.path.basename (fileitem.filename.replace ("\ \", "/"))

File Download dialog box

If we need to provide users with a file download link, and after the user click the link to pop up the file Download dialog box, we set the HTTP header information to implement these functions, the function code is as follows:

#!/usr/bin/python

# HTTP Header

print "Content-type:application/octet-stream; Name=\ "filename\" \ r \ n ";

print "content-disposition:attachment; Filename=\ "filename\" \r\n\n ";

# Actual File Content would go hear.

fo = open ("Foo.txt", "RB")

str = Fo.read ();

Print str

# Close Opend File

Fo.close ()

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.