Tutorials for writing python CGI scripts

Source: Internet
Author: User
Tags python cgi example
Do you want to create a Web page in the Python language, or work with data that users enter from a Web form? These tasks can be implemented through Python CGI (Public gateway Interface) scripts and an Apache Web server. When a user requests a specified URL or interacts with a Web page (such as clicking the "Submit" button), the CGI script is enabled by the Web server. When the CGI script call finishes, its output is used by the Web server to create the Web page that is displayed to the user.
Configure the Apache Web server so that it can run CGI scripts

In this tutorial, we assume that the Apache Web server is already installed and running. This tutorial uses the Apache Web server (version 2.2.15, for CentOS release 6.5) to run on localhost (127.0.0.1), and listens on 80 ports, as specified in the following Apache directives:

The code is as follows:

ServerName 127.0.0.1:80
Listen 80

The HTML file in the following example is stored in the/var/www/html directory on the Web server and is specified by the DocumentRoot directive (the directory where the Web page file is located):

The code is as follows:

DocumentRoot "/var/www/html"

Now try to request url:http://localhost/page1.html

This returns the contents of the following file in the Web server:

The code is as follows:

/var/www/html/page1.html

In order to enable CGI scripting, we must specify the location of the CGI script on the Web server, which requires the Scriptalias directive:

The code is as follows:

scriptalias/cgi-bin/"/var/www/cgi-bin/"

The above instructions indicate that the CGI script is stored in the Web server's/var/www/cgi-bin directory, and the request URL contains/cgi-bin/that will search for CGI scripts in this directory.

We must also make it clear that the CGI script has execute permissions under the/var/www/cgi-bin directory and also specifies the file extension of the CGI script. Use the following directives:

 
 
  
   
    Options +execcgi  AddHandler cgi-script. py 
 
  

Visit url:http://localhost/cgi-bin/myscript-1.py Below

This will invoke the script shown in the Web server as follows:

The code is as follows:

/var/www/cgi-bin/myscript-1.py

Create a CGI script

Before you create a Python CGI script, you need to make sure that you have Python installed (which is usually installed by default, but the installation version may be different). The script used in this tutorial was written using Python version 2.6.6. You can check Python's version by any of the following commands (the-V and--version parameters will display the version number of the python you are installing).

$ PYTHON-V $ python--version

If your Python CGI script is going to handle the data entered by the user (from a Web input form), then you will need to import the Python CGI module. This module can handle the data entered by the user through the Web input form. You can import the script in your script by using the following statement:

Import CGI

You must also modify the Execute permissions of the Python CGI script to prevent the Web server from being called. You can increase execution permissions by using the following command:

# chmod O+x myscript-1.py

Python CGI Example

The two scenarios that involve Python CGI scripts will be described below:

    • Create a Web page with a Python script
    • Reads and displays the data entered by the user and displays the results on the Web page

Note: The Python CGI module is required in scenario 2 because it involves the user entering data from a Web form.
Example 1: Creating a Web page with a Python script

For this scenario, we will start by creating a page/var/www/html/page1.html that contains a single submit button.

  

Test Page 1

When the Submit button is clicked, the/var/www/cgi-bin/myscript-1.py script is called (specified by the action parameter). By setting the method parameter to "get" to specify a "get" request, the server will return the specified Web page. /var/www/html/page1.html is displayed in the browser as follows:

The contents of/var/www/cgi-bin/myscript-1.py are as follows:

#!/usr/bin/python print "content-type:text/html" print "" Print "" Print "

CGI Script Output

"Print"

This page is generated by a Python CGI script.

The first-line declaration indicates that this is a Python script that runs using the/usr/bin/python command. The "content-type:text/html" print statement is required in order for the Web server to know the type of output that is accepted from the CGI script. The rest of the statements are used to output the remaining pages in HTML format.

When the "Submit" button is clicked, the following page will return:

The point of this example is that you can decide what information can be returned by a CGI script. This may include the contents of the log file, the list of currently logged-in users, or today's date. The possibilities for owning all of the Python libraries are endless when you are dealing with them.
Example 2: Read and display the data entered by the user and display the results on the Web page

For this scenario, we'll start by creating a page/var/www/html/page2.html with three input fields and a Submit button.

  

Test Page 2

When the "Submit" button is clicked, the/var/www/cgi-bin/myscript-2.py script will be executed (specified by the action parameter). /var/www//html/page2.html the picture shown in the Web browser is as follows (note that three input fields have been filled in):

The contents of/var/www/cgi-bin/myscript-2.py are as follows:

#!/usr/bin/python import CGI form = CGI. Fieldstorage () print "content-type:text/html" print "print" "Print"

CGI Script Output

"Print"

"Print" The user entered data is:
"Print" FirstName: "+ form[" firstName "].value +"
"Print" LastName: "+ form[" lastName "].value +"
"Print"Position: "+ form[" Position "].value +"
"Print"

"Print" "

As mentioned earlier, the import CGI statement is used to ensure that the data entered by the user through the Web input form is handled. The Web input form is encapsulated in a Form object called a CGI. The Fieldstorage object. Once the output is started, "content-type:text/html" is required because the Web server needs to know the output format that is accepted from the CGI script. The data entered by the user is available in statements containing form["FirstName"].value,form["LastName"].value, and form["position"].value. Those names in brackets are consistent with the name parameters defined in the/var/www/html/page2.html text input field.

When the "Submit" button on the webpage is clicked, the page below will be returned.

The point of this example is that you can easily read and display the data that the user entered on the Web form. In addition to processing data as a string, you can also use Python to convert user-entered data into numbers that can be used for numerical calculations.

  • 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.