目錄
https://www.runoob.com/python3/python3-cgi-programming.html
2.5文件下載對話框
https://www.runoob.com/python3/python3-cgi-programming.html
菜鳥教程
繼上一篇,以下.py文件均放在xampp的cgi-bin下
先解決一下中文亂碼問題:
1.修改apache的httpd.conf文件,新增下面
AddDefaultCharset off
2.原頁面中文亂碼
3.去掉頁面內的下面代碼
4.重啓apache再運行一次
中文顯示正常
1.一個簡單的CGI腳本輸出CGI的環境變量
#!D:/python/python.exe (這裏改成自己的)
# -*- coding: utf-8 -*-
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>")
頁面:
2.GET和POST方法
2.1 GET請求
- GET 請求可被緩存
- GET 請求保留在瀏覽器歷史記錄中
- GET 請求可被收藏爲書籤
- GET 請求不應在處理敏感數據時使用
- GET 請求有長度限制
- GET 請求只應當用於取回數據
#!D:/python/python.exe
# -*- coding: utf-8 -*-
# CGI處理模塊
import cgi
# 創建 FieldStorage 的實例化
form = cgi.FieldStorage()
# 獲取數據
site_name = form.getvalue('name')
site_age = form.getvalue('age')
print("Content-type:text/html")
print()
print("<html>")
print("<head>")
print("<title>菜鳥教程 CGI 測試實例</title>")
print("</head>")
print("<body>")
print("<h2>女朋友名字:%s 年齡:%s</h2>" % (site_name, site_age))
print("</body>")
print("</html>")
打開鏈接:
http://localhost/cgi-bin/get.py?name=ctt&age=19
運行成功
2.1.1用GET的簡單的表單實例
以下是一個通過HTML的表單使用GET方法向服務器發送兩個數據,提交的服務器腳本是get.py文件,get.html 代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鳥教程(runoob.com)</title>
</head>
<body>
<form action="/cgi-bin/get.py" method="get">
女朋友名稱: <input type="text" name="name"> <br />
年齡: <input type="text" name="age" />
<input type="submit" value="提交" />
</form>
</body>
</html>
這個文件放在xampp/htdocs下
點擊:提交
2.2 POST請求
使用POST方法向服務器傳遞數據是更安全可靠的,像一些敏感信息如用戶密碼等需要使用POST傳輸數據。
文件一樣的位置,把get改成了post
2.2.1 通過CGI程序傳遞checkbox數據
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鳥教程(runoob.com)</title>
</head>
<body>
<form action="/cgi-bin/post.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>
#!D:/python/python.exe
# 引入 CGI 處理模塊
import cgi
# 創建 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("<title>菜鳥教程 CGI 測試實例</title>")
print("</head>")
print("<body>")
print("<h2> 菜鳥教程是否選擇了 : %s</h2>" % runoob_flag)
print("<h2> Google 是否選擇了 : %s</h2>" % google_flag)
print("</body>")
print("</html>")
2.3 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.runoob.com"
- 安全secure: 如果給出此標誌,表示cookie只能通過SSL協議的https服務器來傳遞。
- cookie的接收是通過設置環境變量HTTP_COOKIE來實現的,CGI程序可以通過檢索該變量獲取cookie信息。
#!/usr/bin/python3
#
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>
""")
#!/usr/bin/python3
# 導入模塊
import os
import http.cookies
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= http.cookies.SimpleCookie()
# c=Cookie.SimpleCookie()
c.load(cookie_string)
try:
data=c['name'].value
print ("cookie data: "+data+"<br>")
except KeyError:
print ("cookie 沒有設置或者已過去<br>")
print ("""
</body>
</html>
""")
1
2.4文件上傳實例
HTML設置上傳文件的表單需要設置 enctype 屬性爲 multipart/form-data,代碼如下所示:
<!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腳本文件代碼如下:
#!/usr/bin/python3
import cgi, os
import cgitb; cgitb.enable()
form = cgi.FieldStorage()
# 獲取文件名
fileitem = form['filename']
# 檢測文件是否上傳
if fileitem.filename:
# 設置文件路徑
fn = os.path.basename(fileitem.filename)
open('/tmp/' + fn, 'wb').write(fileitem.file.read())
message = '文件 "' + fn + '" 上傳成功'
else:
message = '文件沒有上傳'
print ("""\
Content-Type: text/html\n
<html>
<head>
<meta charset="utf-8">
<title>菜鳥教程(runoob.com)</title>
</head>
<body>
<p>%s</p>
</body>
</html>
""" % (message,))
將以上代碼保存到 save_file.py,並修改 save_file.py 權限:
chmod 755 save_file.py
以上 cookie 設置顏色 Gif 如下所示:
如果你使用的系統是Unix/Linux,你必須替換文件分隔符,在window下只需要使用open()語句即可:
fn = os.path.basename(fileitem.filename.replace("\\", "/" ))
2.5文件下載對話框
我們先在當前目錄下創建 foo.txt 文件,用於程序的下載。
文件下載通過設置HTTP頭信息來實現,功能代碼如下:
#!/usr/bin/python3
# HTTP 頭部
print ("Content-Disposition: attachment; filename=\"foo.txt\"")
print ()
# 打開文件
fo = open("foo.txt", "rb")
str = fo.read();
print (str)
# 關閉文件
fo.close()