Python_012 CGI編程

CGI架構圖(Common Gateway Interface)

cgiarch


Web服務器支持及配置

在你進行CGI編程前,確保您的Web服務器支持CGI及已經配置了CGI的處理程序。html

全部的HTTP服務器執行CGI程序都保存在一個預先配置的目錄。這個目錄被稱爲CGI目錄,並按照慣例,它被命名爲/var/www/cgi-bin目錄。python

CGI文件的擴展名爲.cgi,python也可使用.py擴展名。git

默認狀況下,Linux服務器配置運行的cgi-bin目錄中爲/var/www。web

若是你想指定其餘運行CGI腳本的目錄,能夠修改httpd.conf配置文件,以下所示:編程

<Directory "/var/www/cgi-bin">
   AllowOverride None
   Options ExecCGI
   Order allow,deny
   Allow from all
</Directory>

<Directory "/var/www/cgi-bin">
Options All
</Directory>

第一個CGI程序

咱們使用Python建立第一個CGI程序,文件名爲hellp.py,文件位於/var/www/cgi-bin目錄中,內容以下,修改文件的權限爲755:瀏覽器

#coding=utf-8
#!/usr/bin/python

print "Content-type:text/html\r\n\r\n"
print '<html>'
print '<head>'
print '<title>Hello Word - First CGI Program</title>'
print '</head>'
print '<body>'
print '<h2>Hello Word! This is my first CGI program</h2>'
print '</body>'
print '</html>'

以上程序在瀏覽器訪問顯示結果以下:緩存

Hello Word! This is my first CGI program

這個的hello.py腳本是一個簡單的Python腳本,腳本第一的輸出內容"Content-type:text/html\r\n\r\n"發送到瀏覽器並告知瀏覽器顯示的內容類型爲"text/html"。安全

HTTP頭部

hello.py文件內容中的" Content-type:text/html\r\n\r\n"即爲HTTP頭部的一部分,它會發送給瀏覽器告訴瀏覽器文件的內容類型。服務器

HTTP頭部的格式以下:cookie

HTTP 字段名: 字段內容

例如
Content-type: text/html\r\n\r\n

如下表格介紹了CGI程序中HTTP頭部常常使用的信息:

描述
Content-type: 請求的與實體對應的MIME信息。例如: Content-type:text/html
Expires: Date 響應過時的日期和時間
Location: URL 用來重定向接收方到非請求URL的位置來完成請求或標識新的資源
Last-modified: Date 請求資源的最後修改時間
Content-length: N 請求的內容長度
Set-Cookie: String 設置Http Cookie

CGI環境變量

全部的CGI程序都接收如下的環境變量,這些變量在CGI程序中發揮了重要的做用:

變量名 描述
CONTENT_TYPE 這個環境變量的值指示所傳遞來的信息的MIME類型。目前,環境變量CONTENT_TYPE通常都是:application/x-www-form-urlencoded,他表示數據來自於HTML表單。
CONTENT_LENGTH 若是服務器與CGI程序信息的傳遞方式是POST,這個環境變量即便從標準輸入STDIN中能夠讀到的有效數據的字節數。這個環境變量在讀取所輸入的數據時必須使用。
HTTP_COOKIE 客戶機內的 COOKIE 內容。
HTTP_USER_AGENT 提供包含了版本數或其餘專有數據的客戶瀏覽器信息。
PATH_INFO 這個環境變量的值表示緊接在CGI程序名以後的其餘路徑信息。它經常做爲CGI程序的參數出現。
QUERY_STRING 若是服務器與CGI程序信息的傳遞方式是GET,這個環境變量的值即便所傳遞的信息。這個信息經跟在CGI程序名的後面,二者中間用一個問號'?'分隔。
REMOTE_ADDR 這個環境變量的值是發送請求的客戶機的IP地址,例如上面的192.168.1.67。這個值老是存在的。並且它是Web客戶機須要提供給Web服務器的惟一標識,能夠在CGI程序中用它來區分不一樣的Web客戶機。
REMOTE_HOST 這個環境變量的值包含發送CGI請求的客戶機的主機名。若是不支持你想查詢,則無需定義此環境變量。
REQUEST_METHOD 提供腳本被調用的方法。對於使用 HTTP/1.0 協議的腳本,僅 GET 和 POST 有意義。
SCRIPT_FILENAME CGI腳本的完整路徑
SCRIPT_NAME CGI腳本的的名稱
SERVER_NAME 這是你的 WEB 服務器的主機名、別名或IP地址。
SERVER_SOFTWARE 這個環境變量的值包含了調用CGI程序的HTTP服務器的名稱和版本號。例如,上面的值爲Apache/2.2.14(Unix)

如下是一個簡單的CGI腳本輸出CGI的環境變量:

#coding=utf-8
#!/usr/bin/python

import os

print "Content-type: text/html\r\n\r\n";
print "<font size=+1>Environment</font><\br>";
for param in 
  print "<b>%20s</b>: %s<\br>" % (param, os.environ[param])

GET和POST方法

瀏覽器客戶端經過兩種方法向服務器傳遞信息,這兩種方法就是 GET 方法和 POST 方法。

使用GET方法傳輸數據

GET方法發送編碼後的用戶信息到服務端,數據信息包含在請求頁面的URL上,以"?"號分割, 以下所示:

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

有關 GET 請求的其餘一些註釋:

  • GET 請求可被緩存

  • GET 請求保留在瀏覽器歷史記錄中

  • GET 請求可被收藏爲書籤

  • GET 請求不該在處理敏感數據時使用

  • GET 請求有長度限制

  • GET 請求只應當用於取回數據

簡單的url實例:GET方法

如下是一個簡單的URL,使用GET方法向hello_get.py程序發送兩個參數:

/cgi-bin/hello_get.py?first_name=ZARA&last_name=ALI

如下爲hello_get.py文件的代碼:

#coding=utf-8
#!/usr/bin/python

# CGI處理模塊
import cgi, cgitb 

# 建立 FieldStorage 的實例化


# 獲取數據

last_name  = form.getvalue('last_name')

print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Hello - Second CGI Program</title>"
print "</head>"
print "<body>"
print "<h2>Hello %s %s</h2>" % (first_name, last_name)
print "</body>"
print "</html>"

瀏覽器請求輸出結果:

Hello ZARA ALI

簡單的表單實例:GET方法

如下是一個經過HTML的表單使用GET方法向服務器發送兩個數據,提交的服務器腳本一樣是hello_get.py文件,代碼以下:

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

使用POST方法傳遞數據

使用POST方法向服務器傳遞數據是更安全可靠的,像一些敏感信息如用戶密碼等須要使用POST傳輸數據。

如下一樣是hello_get.py ,它也能夠處理瀏覽器提交的POST表單數據:

#coding=utf-8
#!/usr/bin/python

# 引入 CGI 模塊 
import cgi, cgitb 

# 建立 FieldStorage 實例


# 獲取表單數據

last_name  = form.getvalue('last_name')

print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Hello - Second CGI Program</title>"
print "</head>"
print "<body>"
print "<h2>Hello %s %s</h2>" % (first_name, last_name)
print "</body>"
print "</html>"

如下爲表單經過POST方法向服務器腳本hello_get.py提交數據:

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

經過CGI程序傳遞checkbox數據

checkbox用於提交一個或者多個選項數據,HTML代碼以下:

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

如下爲 checkbox.cgi 文件的代碼:

#coding=utf-8
#!/usr/bin/python

# 引入 CGI 處理模塊 


# 建立 FieldStorage的實例 
form = cgi.FieldStorage() 

# 接收字段數據
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 "<html>"
print "<head>"
print "<title>Checkbox - Third CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> CheckBox Maths is : %s</h2>" % math_flag
print "<h2> CheckBox Physics is : %s</h2>" % physics_flag
print "</body>"
print "</html>"

經過CGI程序傳遞Radio數據

Radio只向服務器傳遞一個數據,HTML代碼以下:

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

radiobutton.py 腳本代碼以下:

#coding=utf-8
#!/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 "<html>"
print "<head>"
print "<title>Radio - Fourth CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> Selected Subject is %s</h2>" % subject
print "</body>"
print "</html>"

經過CGI程序傳遞 Textarea 數據

Textarea向服務器傳遞多行數據,HTML代碼以下:

<form action="/cgi-bin/textarea.py" method="post" target="_blank">
<textarea name="textcontent" cols="40" rows="4">
Type your text here...
</textarea>
<input type="submit" value="Submit" />
</form>

textarea.cgi腳本代碼以下:

#coding=utf-8
#!/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 "<html>"
print "<head>";
print "<title>Text Area - Fifth CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> Entered Text Content is %s</h2>" % text_content
print "</body>"

經過CGI程序傳遞下拉數據

HTML下拉框代碼以下:

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

dropdown.py 腳本代碼以下所示:

#coding=utf-8
#!/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 "<html>"
print "<head>"
print "<title>Dropdown Box - Sixth CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> Selected Subject is %s</h2>" % subject
print "</body>"
print "</html>"

CGI中使用Cookie

在http協議一個很大的缺點就是不做用戶身份的判斷,這樣給編程人員帶來很大的不便,

而cookie功能的出現彌補了這個缺憾。

全部cookie就是在客戶訪問腳本的同時,經過客戶的瀏覽器,在客戶硬盤上寫入紀錄數據 ,當下次客戶訪問腳本時取回數據信息,從而達到身份判別的功能,cookie經常使用在密碼判斷中 。

 

cookie的語法

http cookie的發送是經過http頭部來實現的,他早於文件的傳遞,頭部set-cookie的語法以下:

Set-cookie:name=name;expires=date;path=path;domain=domain;secure
  • name=name: 須要設置cookie的值(name不能使用";"和","號),有多個name值時用";"分隔例如:name1=name1;name2=name2;name3=name3。

  • expires=date: cookie的有效期限,格式: expires="Wdy,DD-Mon-YYYY HH:MM:SS"

  •  

  • path=path: 設置cookie支持的路徑,若是path是一個路徑,則cookie對這個目錄下的全部文件及子目錄生效,例如: path="/cgi-bin/",若是path是一個文件,則cookie指對這個文件生效,例如:path="/cgi-bin/cookie.cgi"。

  • domain=domain: 對cookie生效的域名,例如:domain="www.chinalb.com"

  • secure: 若是給出此標誌,表示cookie只能經過SSL協議的https服務器來傳遞。

  • cookie的接收是經過設置環境變量HTTP_COOKIE來實現的,CGI程序能夠經過檢索該變量獲取cookie信息。


Cookie設置

Cookie的設置很是簡單,cookie會在http頭部單獨發送。如下實例在cookie中設置了UserID 和 Password:

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

以上實例使用了 Set-Cookie 頭信息來設置Cookie信息,可選項中設置了Cookie的其餘屬性,如過時時間Expires,域名Domain,路徑Path。這些信息設置在 "Content-type:text/html\r\n\r\n"以前。


檢索Cookie信息

Cookie信息檢索頁很是簡單,Cookie信息存儲在CGI的環境變量HTTP_COOKIE中,存儲格式以下:

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

如下是一個簡單的CGI檢索cookie信息的程序:

#coding=utf-8
#!/usr/bin/python

# Import modules for CGI handling 
from os import environ
import cgi, cgitb

if environ.has_key('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

以上腳本輸出結果以下:

User ID = XYZ
Password = XYZ123

文件上傳實例:

HTML設置上傳文件的表單須要設置enctype 屬性爲multipart/form-data,代碼以下所示:

<html>
<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>
</html>

save_file.py腳本文件代碼以下:

#coding=utf-8
#!/usr/bin/python

import cgi, os
import cgitb; cgitb.enable()

form = cgi.FieldStorage()

# 獲取文件名


# 檢測文件是否上傳
if fileitem.filename:
   # 設置文件路徑 
   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
<html>
<body>
   <p>%s</p>
</body>
</html>
""" % (message,)

若是你使用的系統是Unix/Linux,你必須替換文件分隔符,在window下只須要使用open()語句便可:

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

文件下載對話框

若是咱們須要爲用戶提供文件下載連接,並在用戶點擊連接後彈出文件下載對話框,咱們經過設置HTTP頭信息來實現這些功能,功能代碼以下:

#coding=utf-8
#!/usr/bin/python


print "Content-Type:application/octet-stream; name=\"FileName\"\r\n";
print "Content-Disposition: attachment; filename=\"FileName\"\r\n\n";

# Actual File Content will go hear.
fo = open("foo.txt", "rb")

str = fo.read();
print str

# Close opend file
fo.close()
相關文章
相關標籤/搜索