一、什麼是CGI?
CGI(通用網關介面)是一種協議,用於Web伺服器和其他軟體(如Python腳本)之間的通信,主要作用是處理HTTP請求並生成響應。
在Web開發中,CGI通常用於處理動態內容,例如Web表單提交、登錄驗證和資料庫查詢等。當用戶訪問包含CGI腳本的網頁時,Web伺服器會將請求傳遞給CGI腳本,腳本則會根據請求的內容動態生成HTML頁面,並將生成的頁面返回給Web伺服器。
二、使用Python編寫CGI腳本
Python是一種功能強大的編程語言,它可以用於編寫Web應用程序的各個方面,包括伺服器端和客戶端。下面我們將介紹如何使用Python編寫簡單的CGI腳本。
1、Hello World
下面是一個簡單的CGI腳本示例,用於產生一個Hello World頁面:
#!/usr/bin/env python3 print("Content-type:text/html") print("") print("<html><head><title>Hello World</title></head><body>") print("<h2>Hello World!</h2>") print("</body></html>")
以上代碼實現了向客戶端輸出HTML代碼的功能,其中第一行指定了輸出內容的類型為text/html,第二行輸出一個空行以分隔頭部和正文,接下來的代碼生成一個包含”Hello World!”標題的HTML頁面。
2、Web表單處理
下面是一個用Python處理Web表單的CGI腳本示例:
#!/usr/bin/env python3 import cgi # 創建FieldStorage實例 form = cgi.FieldStorage() # 獲取表單值 name = form.getvalue('name') # 生成HTML響應 print("Content-type:text/html") print("") print("<html><head><title>Greeting Page</title></head><body>") if name: print("<h2>Welcome, %s!</h2>" % name) else: print("<h2>Please enter your name.</h2>") print("<form action='/cgi-bin/greeting.py' method='post'>") print("<p>Name:<input type='text' name='name'></p>") print("<p><input type='submit' value='Submit'></p>") print("</form>") print("</body></html>")
以上代碼實現了一個簡單的Web表單,用於向用戶索取姓名並輸出歡迎消息。當用戶提交表單時,CGI腳本會從請求中獲取用戶的姓名,並生成一個包含歡迎消息的HTML頁面。
3、資料庫查詢
下面是一個使用Python和SQLite資料庫進行查詢的CGI腳本示例:
#!/usr/bin/env python3 import cgi import sqlite3 # 連接資料庫 conn = sqlite3.connect('test.db') # 創建游標 cursor = conn.cursor() # 獲取表單值 keyword = cgi.FieldStorage().getvalue('keyword') # 查詢資料庫 if keyword: results = cursor.execute("SELECT name, price FROM products WHERE name LIKE ?", ('%'+keyword+'%',)).fetchall() # 生成HTML響應 print("Content-type:text/html") print("") print("<html><head><title>Product Search Results</title></head><body>") print("<h2>Product Search Results</h2>") print("<form action='/cgi-bin/search.py' method='get'>") print("<p>Keyword:<input type='text' name='keyword'><input type='submit' value='Search'></p>") print("</form>") if keyword: if results: print("<table>") print("<tr><th>Name</th><th>Price</th></tr>") for row in results: print("<tr><td>%s</td><td>%s</td></tr>" % row) print("</table>") else: print("<p>No results found</p>") print("</body></html>") # 關閉游標和連接 cursor.close() conn.close()
以上代碼使用了SQLite資料庫,搜索商品名稱包含關鍵字的商品,並輸出結果。CGI腳本從請求中獲取關鍵字,然後使用LIKE語句對資料庫進行查詢,並按照HTML表格的格式呈現結果。注意,為了避免SQL注入攻擊,我們使用了佔位符(?)來構建SQL查詢語句。
三、如何在Web伺服器中運行CGI腳本?
Web伺服器需要配置才能運行CGI腳本。如果使用的是Apache伺服器,可以在httpd.conf文件中添加以下配置:
<Directory "/var/www/cgi-bin"> AllowOverride None Options +ExecCGI Order allow,deny Allow from all AddHandler cgi-script .py </Directory>
以上配置指定了CGI腳本所在的目錄,並將.py文件關聯到CGI程序處理器。在伺服器上安裝Python 3的CGI程序處理器之後,就可以在瀏覽器中訪問CGI腳本了。
四、結語
Python的CGI模塊提供了方便的工具,可以用於實現動態Web應用程序。使用Python編寫CGI腳本可以減少Web開發的複雜度,提高開發效率,同時還可以享受到Python的強大編程能力。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/243088.html