python用于搭建http server的模塊有如下三種:
1)BaseHTTPServer:提供基本的Web服務和處理器類,分別是HTTPServer及BaseHTTPRequestHandler;
2)SimpleHTTPServer:包含執行GET和HEAD請求的SimpleHTTPRequestHandler類;
3)CGIHTTPServer:包含處理POST請求和執行的CGIHTTPRequestHandler類。
python 最簡單的web服務器如下圖所示:
如此便可以訪問服務器中的內容
例如直接訪問下面的html頁面,結果如下:
hello.html存放于服務器根目錄下,代碼如下:
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'> <html><head><title>數據庫列表</title></head> <body> <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> </body></html>
在hello.html文件里面鏈接了一個hello_get.py,該文件存放于服務器根目錄下的cgi-bin文件夾下,代碼如下:
#!/usr/bin/python # Import modules for CGI handling import cgi, cgitb # Create instance of FieldStorage form = cgi.FieldStorage() # Get data from fields first_name = form.getvalue('first_name') last_name = form.getvalue('last_name') print "Content-type:text/html " 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>"
在上一圖片中頁面中輸入信息,點擊提交,得到結果如下:
值得注意的是:一開始我做了好久,調用py文件要么顯示空白,要么出錯。查看了很多網絡資源,發現問題是py文件的權限原因,只需要執行chmod 755 XXX.py即可。此外
#!/usr/bin/python之前最好不要有其他信息,反正我發現上方保護如下信息的時候是顯示不出來的
''' Created on 2015-1-12 @author: root '''
我也只是初學者,只能說把我的學習過程分享,避免大家遇到我同樣問題而花費大量時間。
【相關推薦】
1. 詳解cgi向文本或者數據庫寫入數據實例代碼
2. 分享在IIS上用CGI方式運行Python腳本的實例教程
3. 什么是CGI?詳細介紹Python CGI編程
4. 分享一個PythonCGI編程的實例教程
5. 詳解XML與現代CGI應用程序的示例代碼
6. FastCGI 進程意外退出造成500錯誤
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com