python Web 之基石 - - CGI 编程 (基于python3)
- 一 CGI 編程之前綴篇
- 1CGI 入門簡介
- 2Apache2 的安裝以及配置運(yùn)行環(huán)境搭建
- 二 開始 CGI programming 之旅
- HTTP相關(guān)知識講述 - - - first
- demo 隨后 - - - - second
一 、CGI 編程之前綴篇
1、CGI 入門簡介
CGI:是通用網(wǎng)關(guān)接口(Common Gateway Interface)是一個Web服務(wù)器主機(jī)提供信息服務(wù)的標(biāo)準(zhǔn)接口。通過CGI接口,Web服務(wù)器就能夠獲取客戶端提交的信息,轉(zhuǎn)交給服務(wù)器端的CGI程序進(jìn)行處理,最后返回結(jié)果給客戶端。組成CGI通信系統(tǒng)的是兩部分:一部分是html頁面,就是在用戶端瀏覽器上顯示的頁面。另一部分則是運(yùn)行在服務(wù)器上的CGI程序。
首先,我們應(yīng)該明確的是CGI只是一種接口模式,是現(xiàn)代的web開發(fā)的基礎(chǔ),這里的CGI程序可以是Python腳本,PERL腳本,SHELL腳本,C或者C++程序等。本篇文章會涉及到一些web后端處理程序(python3編寫),一小部分前端H5部分,以及apache2 服務(wù)器的初級使用教程(涵蓋基礎(chǔ)配置,設(shè)置等)。
這里附上一張運(yùn)行示意圖:(如下)2、Apache2 的安裝以及配置(運(yùn)行環(huán)境搭建)
注釋:這里筆者用的是Ubuntu 16.04 + python3.5 +mysql數(shù)據(jù)庫 運(yùn)行環(huán)境
- sudo apt-get install apache2
- 檢查是否成功
- systemctl status apache2
- 第二步,打開你的瀏覽器,在導(dǎo)航欄里輸入 localhost 回車
- 此時,出現(xiàn)Apache2 在Ubuntu 的導(dǎo)航網(wǎng)頁,說明初步成功
接下來,開始配置Apache2 的 CGI 編程環(huán)境,這里先講述一下,默認(rèn)安裝后,有這幾個目錄需要注意一下。/etc/apache2 , /var/www/html ,/var/log/apache2/error(日志文件,經(jīng)常用)
- 為了我們方便編程,于是將編輯目錄放在自己的用戶目錄,不用每次訪問編寫時,都需要sudo提高權(quán)限
apache2在/etc/apache2和/etc/apache2/sites-available兩個文件夾下面分別有apache2.conf和000-default.conf兩個配置文件需要改。然后,在自己的用戶目錄 mkdir -p www/html 和 mkdir -p www/cgi-bin 以后,html 和CGI都放置在相應(yīng)得目錄里面即可。
編輯/etc/apache2/apache2.conf這個文件,找到<DDirectory /var/www/>這個選項(xiàng),把其中的/var/www/修改為/home/chen/www注意這里的chen是筆者的用戶目錄,改成自己的用戶目錄。(原來的配置刪掉或注釋)
-這里是我的一些配置
注:安裝過程如果出現(xiàn)錯誤,實(shí)在不能解決,可重新安裝Apache 恢復(fù)默認(rèn),這里附上,完全卸載的方法 Apache 完全卸載
二 、開始 CGI programming 之旅
注:以下的 CGI 程序運(yùn)行時,都需要使用chmod 755 EXE 提高執(zhí)行權(quán)限,才可以運(yùn)行,下面就不在重復(fù)講述了
1 、HTTP相關(guān)知識講述 - - - first
- HTTP頭部的格式如下:
例如:
Content-type: text/html 即為HTTP頭部的一部分,它告訴瀏覽器文件的內(nèi)容類型是html格式。
- CGI程序HTTP頭部常用信息:
CGI 的相關(guān)環(huán)境變量 — 通過環(huán)境變量進(jìn)行相互通信
GET和POST方法
瀏覽器客戶端通過兩種方法向服務(wù)器傳遞信息,這兩種方法就是 GET 方法和 POST 方法。將在后面結(jié)合代碼講解。
2 、demo 隨后 - - - - second
前三句代碼主要是為了防止中文亂碼,chmod 755 ,在導(dǎo)航欄輸入localhost/cgi-bin/environment.py 即可運(yùn)行
2、- 使用GET方法傳輸數(shù)據(jù)
GET方法發(fā)送編碼后的用戶信息到服務(wù)端,數(shù)據(jù)信息包含在請求頁面的URL上,以”?”號分割, 如下所示:
http://www.test.com/cgi-bin/hello.py?key1=value1&key2=value2 有關(guān) GET 請求的其他一些注釋:
- GET 請求可被緩存
- GET 請求可被收藏為書簽
- GET 請求不應(yīng)在處理敏感數(shù)據(jù)時使用
- GET請求有長度限制 GET 請求只應(yīng)當(dāng)用于取回數(shù)據(jù)
- 簡單的url實(shí)例:GET方法
以下是一個簡單的URL,使用GET方法向hello_get.py程序發(fā)送兩個參數(shù):
/cgi-bin/test.py?name=chen&url=http://Mr.chen’s site
瀏覽器輸入localhost/cgi-bin/test.py?name=chen&url=http://Mr.chen's site 訪問
3 、簡單的表單實(shí)例:GET方法,以下是一個通過HTML的表單使用GET方法向服務(wù)器發(fā)送兩個數(shù)據(jù),提交的服務(wù)器腳本同樣是hello_get.py文件,H5代碼如下:
<!DOCTYPE html> <html><head><meta charset="utf-8"><title> Mr.chen site</title></head><body><form action="/cgi-bin/hello-get.py" method="get">this is www.futhureme.cn. Welcome Mr.chen arrived ! ha ha <br /> 站點(diǎn)名稱: <input type="text" name="name"> <br />站點(diǎn) URL: <input type="text" name="url" /><input type="submit" value="提交 after sure" /></form></body> </html>瀏覽器輸入localhost/hello-get.html 訪問
4 、使用POST方法傳遞數(shù)據(jù),使用POST方法向服務(wù)器傳遞數(shù)據(jù)是更安全可靠的,像一些敏感信息如用戶密碼等需要使用POST傳輸數(shù)據(jù)。
以下同樣是hello_get.py ,它也可以處理瀏覽器提交的POST表單數(shù)據(jù):
#!/usr/bin/python3 import codecs ,sys sys.stdout = codecs.getwriter('utf8')(sys.stdout.buffer)# CGI處理模塊 import cgi, cgitb # 創(chuàng)建 FieldStorage 的實(shí)例化 form = cgi.FieldStorage() # 獲取數(shù)據(jù) 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> Mr.chen </title>") print ("</head>") print ("<body>") print ("<h2>%s官網(wǎng):%s</h2>" % (site_name, site_url)) print ("</body>") print ("</html>")表單通過POST方法(method=”post”)向服務(wù)器腳本 hello_get.py 提交數(shù)據(jù),將上述的 html 中的 改為 method=”post” 即可。
5 、通過CGI程序傳遞checkbox數(shù)據(jù)
checkbox用于提交一個或者多個選項(xiàng)數(shù)據(jù),HTML代碼如下
checkbox.py 文件的代碼為:
#!/usr/bin/python3 # 引入 CGI 處理模塊 import cgi,cgitb# 創(chuàng)建 FieldStorage form = cgi.FieldStorage()# 接收字段數(shù)據(jù) if form.getvalue('google'):google_flag = 'yes' else:google_flag = 'No'if form.getvalue('http://blog.csdn.net/smilejiasmile'):smile_flag = 'yes' else:smile_flag = 'No'print ('Content-type:text/html') print () print ('<html>') print ('<head>') print ('<meta charset = \'utf-8\'>') print ('<title> Mr.chen\'s site </title>') print ('</head>') print ('<body>') print ('<h2> Mr.chen\'s site is choised : %s </h2>'%smile_flag) print ('<h2> Google is choised : %s </h2>' %google_flag) print ('</body>') print ('</html>')改權(quán)限 755 ,瀏覽器輸入`localhost/checkbox.html
6 、通過CGI程序傳遞 Textarea 數(shù)據(jù)
Textarea 向服務(wù)器傳遞多行數(shù)據(jù),HTML代碼如下:
textarea.py 腳本代碼
#!/usr/bin/python3 import codecs ,sys sys.stdout = codecs.getwriter('utf8')(sys.stdout.buffer)# 引入 CGI 處理模塊 import cgi,cgitb# 創(chuàng)建 FieldStorage 的實(shí)例 form = cgi.FieldStorage()# 接收字段數(shù)據(jù) if form.getvalue('textcontent'):text_content = form.getvalue('textcontent') else:text_content = 'nothing'print ('Content-type:text/html') print () print ('<html>') print ('<head>') print ("<meta charset = \'utf-8\'>") print ('<title> The site of Mr.chen </title>') print ('</head>') print ('<body>') print ('<h2> you input content is :<pre> %s </h2>'% text_content) print ('</body>') print ('</html>')7 、通過CGI程序傳遞下拉數(shù)據(jù)框。
HTML 下拉框代碼:
dropdown.py 腳本代碼:
#!/usr/bin/python3 # 引入 CGI 處理模塊 import cgi,cgitb# 創(chuàng)建 FieldStrorage 的實(shí)例 form = cgi.FieldStorage()# 接受字段數(shù)據(jù) if form.getvalue('dropdown'):dropdown_value = form.getvalue('dropdown') else:dropdown_value = 'Nothing'print ("Content-type:text/html") print () print ('<html>') print ('<meta charset = \'utf-8\'>') print ('<title> The site of Mr.chen </title>') print ('</head>') print ('<body>') print ('<h2> your choise is : %s </h2>' % dropdown_value) print ('</body>') print ('</html>')8 、CGI中使用Cookie , cookie 就是在客戶訪問腳本的同時,通過客戶的瀏覽器,在客戶硬盤上寫入紀(jì)錄數(shù)據(jù) ,當(dāng)下次客戶訪問腳本時取回數(shù)據(jù)信息,從而達(dá)到身份判別的功能,cookie 常用在身份校驗(yàn)中。
- cookie的語法
http cookie的發(fā)送是通過http頭部來實(shí)現(xiàn)的,他早于文件的傳遞,頭部set-cookie的語法如下:
- name=name: 需要設(shè)置cookie的值(name不能使用”;”和”,”號),有多個name值時用 “;” 分隔,例如:name1=name1;name2=name2;name3=name3。
- expires=date: cookie的有效期限,格式: expires=”Wdy,DD-Mon-YYYY HH:MM:SS”
- path=path: 設(shè)置cookie支持的路徑,如果path是一個路徑,則cookie對這個目錄下的所有文件及子目錄生效,例如: path=”/cgi-bin/”,如果path是一個文件,則cookie指對這個文件生效,例如:path=”/cgi-bin/cookie.cgi”。
- domain=domain: 對cookie生效的域名,例如:domain=”www.runoob.com”
secure: 如果給出此標(biāo)志,表示cookie只能通過SSL協(xié)議的https服務(wù)器來傳遞。
-cookie的接收是通過設(shè)置環(huán)境變量HTTP_COOKIE來實(shí)現(xiàn)的,CGI程序可以通過檢索該變量獲取cookie信息。
9 、Cookie設(shè)置
Cookie的設(shè)置非常簡單,cookie會在http頭部單獨(dú)發(fā)送。以下實(shí)例在cookie中設(shè)置了name 和 expires:
注意這兒的時間設(shè)置,不要讓cookie過時了就行。
#!/usr/bin/python3 print ('Content-type:text/html') print ("Set-Cookie: name = 'Mr.chen';expires = Wed,1 Dec 2017 18:30:00 GMT") print () print (""" <html><head><meta charset = "utf-8"><title> The site of Mr.chen </title></head><body><h1> Cookie set OK ! </h1></body> </html> """)修改權(quán)限 755 ,瀏覽器運(yùn)行即可完成設(shè)置cookie
以上實(shí)例使用了 Set-Cookie 頭信息來設(shè)置Cookie信息,可選項(xiàng)中設(shè)置了Cookie的其他屬性,如過期時間Expires,域名Domain,路徑Path。這些信息設(shè)置在 “Content-type:text/html”之前。
10 、檢索Cookie信息
Cookie信息檢索頁非常簡單,Cookie信息存儲在CGI的環(huán)境變量HTTP_COOKIE中,存儲格式如下:
key1=value1;key2=value2;key3=value3….
demo 如下:
#!/usr/bin/python3 import codecs ,sys sys.stdout = codecs.getwriter('utf8')(sys.stdout.buffer)# 導(dǎo)入模塊 import os from http import cookiesprint ("Content-type: text/html") print ()print (""" <html><head><meta charset = "utf-8"><title> The sie of chen </title></head><body><h1> reading cookie 信息 </h1> """) if 'HTTP_COOKIE' in os.environ:cookie_string = os.environ.get('HTTP_COOKIE')c = cookies.SimpleCookie()c.load(cookie_string)try: # 捕捉異常data = c['name'].valueprint ("<h2> cookie data: "+ data + "</h2> <br>")except KeyError:print ("cookie 沒有設(shè)置或者已經(jīng)過時 <br>")print ("""</body></html>""")修改權(quán)限 755 ,瀏覽器運(yùn)行即可完成獲取 。
11 、文件上傳實(shí)例
HTML設(shè)置上傳文件的表單需要設(shè)置 enctype 屬性為 multipart/form-data,代碼如下所示:
save_file.py腳本文件代碼:
#!/usr/bin/python3 import cgi,os import cgitb; cgitb.enable()form = cgi.FieldStorage()# 獲取文件名 fileitem = form['filename']# 檢測文件是否上傳 if fileitem.filename:# 設(shè)置文件路徑fn = os.path.basename(filename)open('/tmp/'+fn,'wb').write(fileitem.file.read())message = '文件 "' + fn + '" upload success'else:message = 'no file upload' print("""\Content-Type:text/html\n<html><head><meta charset= 'utf-8'><title> The site of Mr.chen </title></head><body><p>%s </p></body></html>"""%(message,))修改權(quán)限 755 ,瀏覽器運(yùn)行即可。
12 、文件下載對話框
我們先在當(dāng)前目錄下創(chuàng)建 foo.txt 文件,用于程序的下載。
文件下載通過設(shè)置HTTP頭信息來實(shí)現(xiàn),功能代碼如下:
注: 本文參考,自己的學(xué)習(xí)筆記,以及一些網(wǎng)站,如,runoob 等,整合而成。
—- Mr.chen
總結(jié)
以上是生活随笔為你收集整理的python Web 之基石 - - CGI 编程 (基于python3)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java 编程开发
- 下一篇: 【转】【Linux】Linux下统计当前