YouTip LogoYouTip

Python Cgi

Python2.x Python CGI Programming


CGI is currently maintained by NCSA, and NCSA defines CGI as follows: CGI (Common Gateway Interface), the common gateway interface, is a program that runs on the server such as an HTTP server, providing an interface with the client HTML page. > Note: > > > Since Python 3.11, the cgi module has been officially marked as "deprecated" (Deprecated), and will be removed from Python 3.13 onwards. > > > It is recommended to migrate to modern web frameworks such as (#), (#), or (#).

Web Browsing

To better understand how CGI works, we can look at 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 the web server receives the request information, it parses the URL and checks whether the file being accessed exists on the server. If it exists, it returns the content of the file; otherwise, it returns an error message. * 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.

CGI Architecture Diagram

Image 1: cgiarch

Web Server Support and Configuration

Before you perform CGI programming, make sure your web server supports CGI and has the CGI handler configured. Apache supports CGI configuration: Set up the CGI directory: ScriptAlias /cgi-bin/ /var/www/cgi-bin/ All HTTP servers execute 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 Linux servers 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 in AddHandler so that we can access Python script files ending with .py: AddHandler cgi-script .cgi .pl .py

The First CGI Program

We use Python to create our first CGI program, the file name is hello.py, located in the /var/www/cgi-bin directory, and the content is as follows: #!/usr/bin/python# -*- coding: UTF-8 -*-print "Content-type:text/html"print # blank line, tells the server that the header has endedprint ''print ''print ''print 'Hello World - My first CGI program!'print ''print ''print '

Hello World! I am the first CGI program from .com

'print ''print '' After saving the file, modify hello.py and set the file permission to 755: chmod 755 hello.py Accessing the above program in the browser at **http://localhost/cgi-bin/hello.py** will display the following result: Hello World! I am the first CGI program from .com This hello.py script is a simple Python script. The output content in the first line of the script, "Content-type:text/html", is sent to the browser and informs the browser that the content type is "text/html". Using print to output a blank line is used to inform the server that the header information has ended.

HTTP Header

The "Content-type:text/html" in the content of 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 format of the HTTP header is as follows: HTTP field name: field content For example: Content-type: text/html The following table introduces the frequently used information in HTTP headers in CGI programs: | Header | Description | | --- | --- | | Content-type: | The MIME information corresponding to the request entity. 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 non-requested URL location to complete the request or identify a new resource | | Last-modified: Date | The last modification time of the requested resource | | Content-length: N | The length of the request content | | Set-Cookie: String | Sets 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 passed. Currently, the environment variable CONTENT_TYPE is generally: application/x-www-form-urlencoded, which indicates that the data comes from an HTML form. | | CONTENT_LENGTH | If the way the server and CGI program pass information is POST, this environment variable is the number of bytes that can be read from standard input STDIN. This environment variable must be used when reading the input data. | | HTTP_COOKIE | The content of the COOKIE inside the client. | | HTTP_USER_AGENT | Provides the client browser information that includes version numbers or other proprietary data. | | PATH_INFO | The value of this environment variable represents other path information that follows the CGI program name. It often appears as a parameter of the CGI program. | | QUERY_STRING | If the way the server and CGI program pass information is GET, the value of this environment variable is the information passed. This information is placed after the CGI program name, separated by a question mark '?' between them. | | REMOTE_ADDR | The value of this environment variable is the IP address of the client that sent the request, for example, 192.168.1.67 above. This value always exists. And it is the only identifier that the Web client needs to provide to the Web server, which can be used in the CGI program to distinguish different Web clients. | | REMOTE_HOST | The value of this environment variable contains the hostname of the client that sent the CGI request. If it is not supported, there is no need to define this environment variable. | | REQUEST_METHOD | Provides the method by which the script was 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 hostname, 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 the CGI environment variables: #!/usr/bin/python# -*- coding: UTF-8 -*-# filename:test.pyimport os print "Content-type: text/html"printprint ""print "Environment Variables
";print "
    "for key in os.environ.keys(): print "
  • %30s : %s
  • " % (key,os.environ)print "
" Save the above code as test.py, and set the file permission to 755, the execution result is as follows: Image 2

GET and POST Methods

The browser client transmits information to the server through two methods, which are the GET method and the POST method. ### Transmitting Data Using the GET Method The GET method sends encoded user information to the server, and the data information is included in the URL of the request page, separated by a "?" symbol, 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 are retained in the browser history * GET requests can be bookmarked * GET requests should not be used when processing sensitive data * GET requests have length limitations * GET requests 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/test.py?name=&url= The code for the hello_get.py file is as follows: #!/usr/bin/python# -*- coding: UTF-8 -*-# filename:test.py# CGI processing moduleimport 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"printprint ""print ""print ""print ""print ""print ""print "

%s Official Website:%s

" % (site_name, site_url)print ""print "" After saving the file, modify hello_get.py and set the file permission to 755: chmod 755 hello_get.py The output result of the browser request is: Image 3 ### Simple Form Example: GET Method The following is an HTML form that uses the GET method to send two pieces of data to the server, and the server-side script that submits is still the hello_get.py file, the code for hello_get.html is as follows: Site Name:
Site URL: By default, the cgi-bin directory can only store script files. We store hello_get.html in the test directory and set the file permission to 755: chmod 755 hello_get.html The GIF demonstration is as follows: Image 4 ### Transmitting Data Using the POST Method Using the POST method to transmit data to the server is more secure and reliable. Sensitive information such as user passwords should be transmitted using POST. The following is the same hello_get.py, which can also handle the POST form data submitted by the browser: #!/usr/bin/python# -*- coding: UTF-8 -*-# CGI processing moduleimport cgi, cgitb # Create an instance of FieldStorage form = cgi.FieldStorage() # Get data site_name = form.getvalue('name') site_url =
← Att String ReplaceAtt String Max β†’