Python study notes -Python CGI programming

What is CGI

The CGI ( C ommon G ateway the I nterface), Common Gateway Interface, which is a program, running on the server on such as: HTTP server, the client interface provides the same HTML page.

CGI currently consists of NCSA (National Computer Security Association ( N ational C omputer S ecurity A maintenance ssociation))


Web surfing

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

  • 1, use your browser to access the URL and connect to the HTTP web server .
  • 2, Web server receives the request will parse URL information , and to find whether there is access files on the server, if there is return the contents of the file, otherwise it returns an error message.
  • 3, the browser receives the information from the server and displays the received file or an error message.

CGI programs can be a Python script, PERL script, SHELL script, C or C ++ programs.


CGI Chart

cgiarch


Web server configuration and support

Before you make CGI programming, ensure that your Web server has been configured to support CGI and CGI handler.

Apache supports CGI configuration:

Set up the CGI directory:

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

All the HTTP server execute a CGI programs are stored in a preconfigured directory --CGI directory , and by convention, it is named / var / www / cgi-bin directory.

CGI file name extension  .cgi , you can use Python  .py  extension.

By default, cgi-bin directory Linux server is configured to run in / var / www.

If you want to specify a directory other 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>

Add .py suffix AddHandler, so that we can access at the end of .py python script file:

AddHandler cgi-script .cgi .pl .py

The first CGI program

We use Python to create the first CGI program called hello.py, the file is located in / var / www / cgi-bin directory, as follows:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

print "Content-type:text/html"
print                               # 空行,告诉服务器结束头部
print '<html>'
print '<head>'
print '<meta charset="utf-8">'
print '<title>Hello World - 我的第一个 CGI 程序!</title>'
print '</head>'
print '<body>'
print '<h2>Hello World! 我是来自菜鸟教程的第一CGI程序</h2>'
print '</body>'
print '</html>'

After you save the modified file hello.py, modify the file permissions to 755:

chmod 755 hello.py 

Above to access the browser  http: //localhost/cgi-bin/hello.py  display is as follows:

 

Hello World! I was the first CGI program from rookie tutorial

The hello.py this script is a simple Python script, output from the first line of the script "Content-type: text / html" to the browser and the browser displays inform the content type is "text / html".

Print output with a blank line is used to tell the server end of the header information.


HTTP header

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

HTTP header of the following format:

HTTP field names: Field Contents

E.g:

Content-type: text/html

The following table describes the information in the HTTP headers CGI program is often used:

head description
Content-type: MIME entity information corresponding to the request. For example: Content-type: text / html
Expires: Date In response date and time expired
Location: URL The recipient to redirect unsolicited location URL or request to complete a new resource identifier
Last-modified: Date The last modification time of the requested resource
Content-length: N Requested content length
Set-Cookie: String Set Http Cookie

CGI Environment Variables

All the CGI program receives the following environmental variables play an important role in the CGI program:

variable name description
CONTENT_TYPE The MIME type for this value indicates the information transfer environment variable. At present, the environment variables are generally CONTENT_TYPE: application / x-www-form-urlencoded, he said that data from the HTML form.
CONTENT_LENGTH If the transfer mode information server CGI program is POST, even if the number of bytes in this environment variable STDIN valid data can be read from the standard input. This environment variable must be used when reading the input data.
HTTP_COOKIE COOKIE content within the client.
HTTP_USER_AGENT Provide information contains the customer browser version number or other proprietary data.
PATH_INFO This represents the value of the environment variable name immediately after the CGI program of additional path information. It often appears as a parameter CGI program.
QUERY_STRING If the transfer mode server and CGI program information is information GET, the value of the environment variable even if passed. This information is followed by the CGI program name, a question mark by the middle of the two '?' Separated.
REMOTE_ADDR The environment variable is the IP address of the client sends a request, for example, the above 192.168.1.67. This value is always present. And it is the only identifies the need to provide Web client to the Web server, it can be used to distinguish between different Web client using CGI program.
REMOTE_HOST The value of the environment variable contains the host name of the CGI request of the client. If it does not you want to check, you do not need to define this environment variable.
REQUEST_METHOD To provide a method called script. For the script uses HTTP / 1.0 protocol, only GET and POST meaningful.
SCRIPT_FILENAME Full path to 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 the environment variable contains the name and version number of the HTTP server calls the CGI program. For example, the above value of Apache / 2.2.14 (Unix)

Here is a simple CGI script output CGI environment variables:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# filename:test.py

import os

print "Content-type: text/html"
print
print "<meta charset=\"utf-8\">"
print "<b>环境变量</b><br>";
print "<ul>"
for key in os.environ.keys():
    print "<li><span style='color:green'>%30s </span> : %s </li>" % (key,os.environ[key])
print "</ul>"

Save the above points test.py, and modify the file permissions to 755, the results are as follows:


GET and POST methods

Browser client to the server to transmit information in two ways, both of which method is GET and POST methods.

Using the GET method for transmitting data

GET method transmits the encoded user information to the server, data comprising information on the URL of the requested page (URL pass value), to division number, as shown below, "?":

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

GET requests related to some of the other comments:

  • GET request can be cached
  • GET requests remain in browser history
  • GET requests can be bookmarked
  • GET requests should not be used when processing sensitive data
  • GET requests have length restrictions
  • GET requests should only be used to retrieve data

Simple url example: GET method

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

/cgi-bin/test.py?name= rookie tutorial & url = http: //www.runoob.com

The following is the code hello_get.py file:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# filename:test.py

# CGI处理模块
import cgi, cgitb 

# 创建 FieldStorage 的实例化
form = cgi.FieldStorage() 

# 获取数据
site_name = form.getvalue('name')
site_url  = form.getvalue('url')

print "Content-type:text/html"
print
print "<html>"
print "<head>"
print "<meta charset=\"utf-8\">"
print "<title>菜鸟教程 CGI 测试实例</title>"
print "</head>"
print "<body>"
print "<h2>%s官网:%s</h2>" % (site_name, site_url)
print "</body>"
print "</html>"

After you save the modified file hello_get.py, modify the file permissions to 755:

chmod 755 hello_get.py 

Browser requests the output:

Examples of simple form: GET method

The following is a two transmitting data to the server by using the GET method of the HTML form, the server script file submitted likewise hello_get.py, hello_get.html code is as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<form action="/cgi-bin/hello_get.py" method="get">
站点名称: <input type="text" name="name">  <br />

站点 URL: <input type="text" name="url" />
<input type="submit" value="提交" />
</form>
</body>
</html>

cgi-bin directory can only store script files by default, we will test directory, modify the file permissions hello_get.html memory 755:

chmod 755 hello_get.html

Gif presentation as follows:

Method of communicating data using the POST

Using the POST method of communicating data to a server is more secure and reliable, sensitive information, such as user password required to transfer data POST.

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

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# CGI处理模块
import cgi, cgitb 

# 创建 FieldStorage 的实例化
form = cgi.FieldStorage() 

# 获取数据
site_name = form.getvalue('name')
site_url  = form.getvalue('url')

print "Content-type:text/html"
print
print "<html>"
print "<head>"
print "<meta charset=\"utf-8\">"
print "<title>菜鸟教程 CGI 测试实例</title>"
print "</head>"
print "<body>"
print "<h2>%s官网:%s</h2>" % (site_name, site_url)
print "</body>"
print "</html>"

The following is a form via POST method ( Method, = "POST" submit data to the server script hello_get.py):

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<form action="/cgi-bin/hello_get.py" method="post">
站点名称: <input type="text" name="name">  <br />

站点 URL: <input type="text" name="url" />
<input type="submit" value="提交" />
</form>
</body>
</html>

Gif presentation as follows:

Data transferred through the CGI program checkbox

checkbox options for submitting one or more data, HTML code is as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<form action="/cgi-bin/checkbox.py" method="POST" target="_blank">
<input type="checkbox" name="runoob" value="on" /> 菜鸟教程
<input type="checkbox" name="google" value="on" /> Google
<input type="submit" value="选择站点" />
</form>
</body>
</html>

The following is the code checkbox.py file:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 引入 CGI 处理模块 
import cgi, cgitb 

# 创建 FieldStorage的实例 
form = cgi.FieldStorage() 

# 接收字段数据
if form.getvalue('google'):
   google_flag = "是"
else:
   google_flag = "否"

if form.getvalue('runoob'):
   runoob_flag = "是"
else:
   runoob_flag = "否"

print "Content-type:text/html"
print
print "<html>"
print "<head>"
print "<meta charset=\"utf-8\">"
print "<title>菜鸟教程 CGI 测试实例</title>"
print "</head>"
print "<body>"
print "<h2> 菜鸟教程是否选择了 : %s</h2>" % runoob_flag
print "<h2> Google 是否选择了 : %s</h2>" % google_flag
print "</body>"
print "</html>"

Modify checkbox.py permissions:

chmod 755 checkbox.py

Gif browser to access the demo map:

Radio data transmission through the CGI program

Radio transmitting data only to a server, HTML code is as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<form action="/cgi-bin/radiobutton.py" method="post" target="_blank">
<input type="radio" name="site" value="runoob" /> 菜鸟教程
<input type="radio" name="site" value="google" /> Google
<input type="submit" value="提交" />
</form>
</body>
</html>

radiobutton.py script code is as follows:

! # / usr / bin / Python 
# - * - Coding: UTF-. 8 - * - 

# CGI processing module incorporated 
Import CGI, the cgitb 

# Create instance FieldStorage 
form cgi.FieldStorage = () 

# field of the received data 
if form.getvalue ( 'Site'): 
   Site = form.getvalue ( 'Site') 
the else: 
   Site = "submit data empty" 

Print "the Content-type: text / HTML" 
Print 
Print "<HTML>" 
Print "<head>" 
Print " <Meta charset = \ "UTF-8 \"> " 
Print" <title> rookie tutorial CGI test case </ title> " 
Print" </ head> " 
Print" <body> " 
Print" <h2> selected site is S% </ H2> "Site% 
Print" </ body> "
print "</html>"

Modify radiobutton.py permissions:

chmod 755 radiobutton.py

Gif browser to access the demo map:

Data transferred through the CGI program Textarea

Textarea multiple rows of data transmitted to the server, HTML code is as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<form action="/cgi-bin/textarea.py" method="post" target="_blank">
<textarea name="textcontent" cols="40" rows="4">
在这里输入内容...
</textarea>
<input type="submit" value="提交" />
</form>
</body>
</html>

textarea.py script code is as follows:

! # / usr / bin / Python 
# - * - Coding: UTF-. 8 - * - 

# CGI processing module incorporated 
Import CGI, the cgitb 

# Create instance FieldStorage 
form cgi.FieldStorage = () 

# field of the received data 
if form.getvalue ( 'TextContent'): 
   TEXT_CONTENT = form.getvalue ( 'TextContent') 
the else: 
   TEXT_CONTENT = "no content" 

Print "the content-type: text / HTML" 
Print 
Print "<HTML>" 
Print "<head>"; 
Print "< Meta charset = \ "UTF-. 8 \"> " 
Print" <title> novice tutorial CGI test examples </ title> " 
Print" </ head> " 
Print" <body> " 
Print" <content h2> entered: % s </ h2> "% text_content
print "</body>"
print "</html>"

Modify textarea.py permissions:

chmod 755 textarea.py

Gif browser to access the demo map:

Down data transmitted by the CGI program.

Drop-down box HTML code is as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<form action="/cgi-bin/dropdown.py" method="post" target="_blank">
<select name="dropdown">
<option value="runoob" selected>菜鸟教程</option>
<option value="google">Google</option>
</select>
<input type="submit" value="提交"/>
</form>
</body>
</html>

dropdown.py script code as follows:

! # / usr / bin / Python 
# - * - Coding: UTF-. 8 - * - 

# CGI processing module incorporated 
Import CGI, the cgitb 

# Create instance FieldStorage 
form cgi.FieldStorage = () 

# field of the received data 
if form.getvalue ( 'DropDown'): 
   dropdown_value = form.getvalue ( 'DropDown') 
the else: 
   dropdown_value = "no content" 

Print "the content-type: text / HTML" 
Print 
Print "<HTML>" 
Print "<head>" 
Print "<Meta charset = \ "UTF-. 8 \"> " 
Print" <title> novice tutorial CGI test examples </ title> " 
Print" </ head> " 
Print" <body> " 
Print" <H2> selected options are:% s </ h2> "% dropdown_value
print "</body>"
print "</html>"

Modify dropdown.py permissions:

chmod 755 dropdown.py

Gif browser to access the demo map:


CGI is used Cookie

Is not the user's identity in the http protocol a big disadvantage judgment, such a great deal of inconvenience to the programmer, and the emergence cookie functionality made up for this deficiency.

cookie that is, while customers access the script, by the customer's browser, written on the client hard disk record data, retrieve data when customers visit next script, so as to achieve identity discrimination function, the cookie is often used in identity verification.

 

cookie syntax

Send http cookie is achieved through http head, he had to transfer files, set-cookie header syntax is as follows:

Set-cookie:name=name;expires=date;path=path;domain=domain;secure 
  • name = name:  to set the value of the cookie (name can not be used " ; " and " , " number), name when a plurality of values " ; " separated, for example: NAME1 = NAME1; NAME2 = NAME2; NAME3 = NAME3 .
  • DATE = Expires:  Cookie expiration date format: expires = "Wdy, DD- Mon-YYYY HH: MM: SS"
  •  
  • path = path:  Set the path to cookie support, if path is a path, the cookie of all files and subdirectories in this directory into force, for example: path = "/ cgi-bin /", if the path is a file, cookie It refers to the entry into force of this file, for example: path = "/ cgi-bin / cookie.cgi".
  • domain = domain:  the domain name cookie is valid, such as: domain = "www.runoob.com"
  • secure:  If this flag is given that the cookie can only be transferred through https server SSL protocol.
  • cookie is received by setting environment variables HTTP_COOKIE achieved, CGI program can access information by searching the cookie variable.

Cookie settings

Cookie's very easy to set, cookie will be sent separately at http header. The following examples set name and expires in a cookie:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 
print 'Content-Type: text/html'
print 'Set-Cookie: name="菜鸟教程";expires=Wed, 28 Aug 2016 18:30:00 GMT'
print
print """
<html>
    <head>
        <meta charset="utf-8">
        <title>菜鸟教程(runoob.com)</title>
    </head>
    <body>
        <h1>Cookie set OK!</h1>
    </body>
</html>
"""

Save the code above to cookie_set.py, and modify cookie_set.py permissions:

chmod 755 cookie_set.py

Examples of the use of the above Set-Cookie header information to set Cookie information option is set in the Cookie other properties, such as the Expires time expired, the domain name Domain, path Path. This information is set: Before "Content-type text / html".


Cookie Information Retrieval

Cookie information retrieval page is very simple, the environment variable HTTP_COOKIE CGI, the storage format is as follows Cookie information is stored:

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

Here is a simple CGI program to retrieve cookie information:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 导入模块
import os
import Cookie

print "Content-type: text/html"
print

print """
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<h1>读取cookie信息</h1>
"""

if 'HTTP_COOKIE' in os.environ:
    cookie_string=os.environ.get('HTTP_COOKIE')
    c=Cookie.SimpleCookie()
    c.load(cookie_string)

    try:
        data=c['name'].value
        print "cookie data: "+data+"<br>"
</ body>
        Print "is not set or the cookie has expired <br>"
    KeyError the except:
Print "" "
</html>

"""

Save the code above to cookie_get.py, and modify cookie_get.py permissions:

chmod 755 cookie_get.py

Gif color cookie provided above as follows:

Examples of file uploads

Set HTML file to upload to set  enctype  attribute  multipart / form-Data , code as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
 <form enctype="multipart/form-data" 
                     action="/cgi-bin/save_file.py" method="post">
   <p>选中文件: <input type="file" name="filename" /></p>
   <p><input type="submit" value="上传" /></p>
   </form>
</body>
</html>

save_file.py script code is as follows:

! # / usr / bin / Python 
# - * - Coding: UTF-. 8 - * - 

Import CGI, OS 
Import the cgitb; cgitb.enable () 

form = cgi.FieldStorage () 

# get file name 
fileitem = form [ 'filename' ] 

# detects whether a file upload 
iF fileitem.filename: 
   # file path set 
   Fn = os.path.basename (fileitem.filename) 
   . Open ( '/ tmp /' + Fn, 'WB') Write (fileitem.file.read ( )) 

   Message = 'file "' + fn + '" uploaded successfully' 
   
the else: 
   Message = 'file not uploaded' 
   
Print "" "\ 
the Content-the Type: text / HTML \ n- 
<HTML> 
<head> 
<Meta charset =" . 8-UTF "> 
<title> novice tutorial (runoob.com) </ title> 
</ head> 
<body>
   <p>%s</p>
</body>
</html>
""" % (message,)

Save the code above to save_file.py, and modify save_file.py permissions:

chmod 755 save_file.py

Gif color cookie provided above as follows:

If you are using Unix / Linux, you must replace the file delimiters, just use the open in the window () statement to:

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

File Download dialog box

We create foo.txt file in the current directory for downloading the program.

Achieved by setting file download HTTP header, function code is as follows:

! # / usr / bin / Python 
# - * - Coding: UTF-8 - * - 

# HTTP header 
Print "Content-Disposition: Attachment; filename = \" foo.txt \ ""; 
Print 
# open file 
fo = open ( "foo.txt", "RB") 

STR = fo.read (); 
Print STR 

# close the file 
fo.close ()
Published 19 original articles · won praise 0 · Views 803

Guess you like

Origin blog.csdn.net/weixin_44151772/article/details/104057067