Python CGI programming

Source: Internet
Author: User
Tags file separator http cookie set cookie

Python CGI programming
Web browsing

To better understand how CGI works, we can click a link or URL on the webpage:

'Print' 'Print ''print 'Hello Word! This is my first CGI program 'print ''print '"print" "print" "Print" Hello % s "% (first_name, last_name) print" "print" "Print" Hello % s "% (first_name, last_name) print" "print" "Print" CheckBox Maths is: % s "% math_flag print" CheckBox Physics is: % s "% physics_flag print" "print" "Print" Selected Subject is % s "% subject print" "; print" "Print" Entered Text Content is % s "% text_content print" "print" "print" "Print" Selected Subject is % s "% subject print" "print"

% S

  • 1. Use your browser to access the URL and connect to the HTTP web server.
  • 2. After receiving the request information, the Web server parses the URL and finds whether the accessed file exists on the server. If the content of the returned file exists, the Web server returns an error message.
  • 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.

    CGI Architecture

    Web server support and Configuration

    Before you program CGI, make sure that your Web server supports CGI and that the CGI processing program has been configured.

    Apache supports CGI Configuration:

    Set the CGI directory:

    ScriptAlias /cgi-bin/ /var/www/cgi-bin/

    All HTTP servers run CGI programs in a pre-configured directory. This directory is called the CGI directory and is named as the/var/www/cgi-bin directory by convention.

    The CGI file extension is. cgi. python can also use the. py extension.

    By default,/var/www is in the cgi-bin directory of the Linux server.

    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 the python script file ending with. py:

    AddHandler cgi-script .cgi .pl .py
    The first CGI program

    We use Python to create the first CGI program named hello. py. The file is located in the/var/www/cgi-bin directory. The content is as follows. Modify the File Permission to 755:

    #!/usr/bin/python# -*- coding: UTF-8 -*-print "Content-type:text/html\r\n\r\n"print '
    '

    The above results are displayed in the browser:

    Hello Word! This is my first CGI program

    Hello. the py script is a simple Python script. The output Content of the first line of the script is "Content-type: text/html \ r \ n "is sent to the browser and the type of content displayed by the browser is" text/html ".

    HTTP Header

    Hello. content-type: text/html \ r \ n In The py file Content is part of the HTTP header, which is 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: Content of the field, such as Content-type: text/html \ r \ n

    The following table describes frequently used HTTP headers in CGI programs:

    Header Description
    Content-type: The MIME information of the request and the object. For example, Content-type: text/html
    Expires: Date Response expiration date and time
    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 Last modification time of the requested resource
    Content-length: N Request Content Length
    Set-Cookie: String Set Http Cookie
    CGI Environment Variable

    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 passed. Currently, the environment variables CONTENT_TYPE are generally application/x-www-form-urlencoded, which indicates that the data comes from the HTML form.
    CONTENT_LENGTH If the transfer method of the server and CGI program information 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 to read the input data.
    HTTP_COOKIE The COOKIE content in the client.
    HTTP_USER_AGENT Provides the client browser information that contains the version number or other proprietary data.
    PATH_INFO The value of this environment variable indicates other path information that follows the CGI program name. It is often used as a parameter of the CGI program.
    QUERY_STRING If the information transmitted between the server and CGI program is GET, the value of this environment variable is even if the information is transmitted. This information is followed by the CGI program name, and a question mark is used between the two '? .
    REMOTE_ADDR The value of this environment variable is the IP address of the client sending the request, for example, 192.168.1.67 above. This value always exists. Moreover, it is the unique identifier that the Web Client must provide to the Web server. 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 you do not want to query, you do not need to define this environment variable.
    REQUEST_METHOD Provides methods for calling scripts. For scripts using HTTP/1.0, only GET and POST make sense.
    SCRIPT_FILENAME Complete CGI script path
    SCRIPT_NAME CGI Script Name
    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 preceding value is Apache/2.2.14 (Unix)

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

    #!/usr/bin/python# -*- coding: UTF-8 -*-import osprint "Content-type: text/html\r\n\r\n";print "Environment<\br>";for param in os.environ.keys():  print "%20s: %s<\br>" % (param, os.environ[param])
    GET and POST Methods

    The browser client transmits information to the server in two ways, namely 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 contained in the URL of the Request page "? ", As shown below:

    http://www.test.com/cgi-bin/hello.py?key1=value1&key2=value2
    Other notes about GET requests:
    • GET requests can be cached
    • GET requests are retained in browser history
    • GET requests can be added to favorites as bookmarks
    • GET requests should not be used when processing sensitive data
    • GET request length limit
    • GET requests should only be used to retrieve simple url instances: GET Method

      The following is a simple URL. Use 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 code for the hello_get.py file is as follows:

      #! /Usr/bin/python #-*-coding: UTF-8-*-# CGI processing module import cgi, cgitb # create FieldStorage instantiation form = cgi. fieldStorage () # obtain data first_name = form. getvalue ('first _ name') last_name = form. getvalue ('Last _ name') print "Content-type: text/html \ r \ n" print"
      "

      Browser request output result:

      Hello ZARA ALI
      Simple Form example: GET Method

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

      Use the POST method to transmit data

      Using the POST method to transmit data to the server is more secure and reliable. For example, some sensitive information such as user passwords must be transmitted using POST.

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

      #! /Usr/bin/python #-*-coding: UTF-8-*-# import CGI Module import cgi, cgitb # create FieldStorage instance form = cgi. fieldStorage () # obtain the form data first_name = form. getvalue ('first _ name') last_name = form. getvalue ('Last _ name') print "Content-type: text/html \ r \ n" print"
      "

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

      Passing checkbox data through CGI program

      Checkbox is used to submit one or more option data. The HTML code is as follows:

      The code for the checkbox. cgi file is as follows:

      #! /Usr/bin/python #-*-coding: UTF-8-*-# introduce CGI processing module import cgi, cgitb # create FieldStorage instance form = cgi. fieldStorage () # receives 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" print"
      "Transmit Radio data through CGI program

      Radio only transmits one data to the server. The HTML code is as follows:

      The script code of radiobutton. py is as follows:

      #!/usr/bin/python# -*- coding: UTF-8 -*-# Import modules for CGI handling import cgi, cgitb # Create instance of FieldStorage form = cgi.FieldStorage() # Get data from fieldsif form.getvalue('subject'):   subject = form.getvalue('subject')else:   subject = "Not set"print "Content-type:text/html\r\n\r\n"print "
      "Passing Textarea data through CGI program

      Textarea transmits multiple lines of data to the server. The HTML code is as follows:

      The textarea. cgi script code is as follows:

      #!/usr/bin/python# -*- coding: UTF-8 -*-# Import modules for CGI handling import cgi, cgitb # Create instance of FieldStorage form = cgi.FieldStorage() # Get data from fieldsif form.getvalue('textcontent'):   text_content = form.getvalue('textcontent')else:   text_content = "Not entered"print "Content-type:text/html\r\n\r\n"print "
      Passing drop-down data through CGI program

      The code of the HTML drop-down box is as follows:

      The dropdown. py script code is as follows:

      #!/usr/bin/python# -*- coding: UTF-8 -*-# Import modules for CGI handling import cgi, cgitb # Create instance of FieldStorage form = cgi.FieldStorage() # Get data from fieldsif form.getvalue('dropdown'):   subject = form.getvalue('dropdown')else:   subject = "Not entered"print "Content-type:text/html\r\n\r\n"print "
      " Use Cookie in CGI

      A major disadvantage of http protocol is that it does not judge the user identity, which brings great inconvenience to programmers,

      The appearance of the cookie function makes up for this defect.

       

      All cookies are used to write record data on the client's hard disk through the client's browser while the client accesses the script. When the client accesses the script the next time, the data information is retrieved to identify the user, cookies are often used in password determination.

      Cookie syntax

      The http cookie is sent through the http header, Which is earlier than the file transfer. The header's set-cookie syntax is as follows:

      Set-cookie:name=name;expires=date;path=path;domain=domain;secure 
      • Name = name: the cookie value needs to be set (";" and ",", "cannot be used for name). If there are multiple name values, separate them with"; ", for example, name1 = name1; name2 = name2; name3 = name3.
      • Expires = date: cookie validity period. Format: expires = "Wdy, DD-Mon-yyyy hh: MM: SS"
      •  
      • Path = path: set the path supported by the cookie. If the path is a path, the cookie takes effect 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 takes effect for the cookie, for example: domain = "www.chinalb.com"
      • Secure: If this flag is provided, the cookie can only be transmitted through the https server of the SSL protocol.
      • Cookie receiving is implemented by setting the environment variable HTTP_COOKIE. The CGI program can retrieve the cookie information by searching the variable. Cookie settings

        The Cookie setting is very simple. The cookie will be sent separately in the http header. The following instances set the UserID and Password in the cookie:

        #!/usr/bin/python # -*- coding: UTF-8 -*- 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.w3cschool.cc;\r\n" print "Set-Cookie:Path=/perl;\n" print "Content-type:text/html\r\n\r\n" ...........Rest of the HTML Content....

        The preceding example uses the Set-Cookie header information to Set Cookie information. Other attributes of the Cookie, such as the expiration time Expires, Domain name Domain, and Path, are Set in the options. This information is set before "Content-type: text/html \ r \ n.

        Retrieve Cookie Information

        The Cookie information retrieval page is very simple. The Cookie information is stored in the CGI Environment Variable HTTP_COOKIE. The storage format is as follows:

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

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

        #!/usr/bin/python# -*- coding: UTF-8 -*-# Import modules for CGI handling from os import environimport cgi, cgitbif environ.has_key('HTTP_COOKIE'):   for cookie in map(strip, split(environ['HTTP_COOKIE'], ';')):      (key, value ) = split(cookie, '=');      if key == "UserID":         user_id = value      if key == "Password":         password = valueprint "User ID  = %s" % user_idprint "Password = %s" % password

        The output result of the above script is as follows:

        User ID = XYZPassword = XYZ123

        File Upload instance:

        To set the form for uploading files in HTML, you must set the enctype attribute to multipart/form-data. The Code is as follows:

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

        #! /Usr/bin/python #-*-coding: UTF-8-*-import cgi, osimport cgitb; cgitb. enable () form = cgi. fieldStorage () # obtain the file name fileitem = form ['filename'] # Check whether the file is uploaded if fileitem. filename: # Set the 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
        "% (Message ,)

        If the system you are using is Unix/Linux, you must replace the file separator. In the window, you only need to use the open () Statement:

        fn = os.path.basename(fileitem.filename.replace("\\", "/" ))
        File Download Dialog Box

        Create the foo.txt file in the current directory for program download.

        File Download is implemented by setting the HTTP header information. The function code is as follows:

        #! /Usr/bin/python #-*-coding: UTF-8-*-# HTTP header print "Content-Disposition: attachment; filename = \ "foo.txt \" \ r \ n "; # open the file fo = open (" foo.txt "," rb ") str = fo. read (); print str # close the file fo. close ()

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.