一、CGI基礎
CGI(Common Gateway Interface)是WEB伺服器與執行程序之間的一種介面。通過CGI,WEB伺服器可以把用戶請求發送給後端的程序處理,再將處理結果返回給用戶。CGI腳本通常使用Perl、Python等腳本語言編寫。Python標準庫中含有CGI模塊,使用它可以很方便地編寫CGI腳本。下面是一個示例:
#!/usr/bin/python # coding=utf8 import cgi # 輸出HTTP頭部 print("Content-type:text/html") print() # 輸出頁面內容 print("<html><head><title>Hello World - First CGI Program</title></head>") print("<body>") print("<h2>Hello World! This is my first CGI program using Python</h2>") print("</body>") print("</html>")
在上面的示例中,我們使用 Python 內置的 cgi 模塊,它提供了處理 CGI 請求的功能。其中,我們使用常量 Content-type 來輸出 HTTP 響應頭部,在 http 頭部之後必須再輸出一個空行。
二、獲取表單數據
在Web開發中,我們經常需要使用表單來收集用戶輸入的信息。CGI腳本可以從表單中獲取數據。運用Python編寫的CGI腳本可以通過 cgi.FieldStorage() 方法獲取表單數據。
下面是一個示例:
#!/usr/bin/python # coding=utf8 import cgi # 獲取表單數據 form = cgi.FieldStorage() name = form.getvalue("name") age = form.getvalue("age") # 輸出HTTP頭部 print("Content-type:text/html") print() # 輸出頁面內容 print("<html><head><title>Hello {} - CGI Program</title></head>".format(name)) print("<body>") print("<h2>Name: {}</h2>".format(name)) print("<h2>Age: {}</h2>".format(age)) print("</body>") print("</html>")
在上面的示例中,我們獲取了表單中的 name 和 age 兩個值,並在頁面中輸出它們。
三、與資料庫交互
CGI腳本還可以與資料庫交互。Python中有很多資料庫模塊可以使用,比如 MySQL-Python、PyMySQL、psycopg2 等等。本例中以 MySQL 為例。
在執行下面的代碼之前,需要首先在你的機器上安裝 MySQL 資料庫,並在 Python 環境中安裝好 MySQL-Python 模塊。
首先,在 MySQL 中創建一個名為 test 的資料庫,並在其中創建一張名為 user 的表:
CREATE DATABASE test; USE test; CREATE TABLE user( id INT(11) PRIMARY KEY AUTO_INCREMENT, name VARCHAR(50), age INT(11) );
接著,編寫一個用於將表單數據插入資料庫的 CGI 腳本:
#!/usr/bin/python # coding=utf8 import cgi import MySQLdb # 獲取表單數據 form = cgi.FieldStorage() name = form.getvalue("name") age = form.getvalue("age") # 向MySQL中插入數據 db = MySQLdb.connect("localhost", "root", "password", "test") cursor = db.cursor() sql = "INSERT INTO user(name, age) VALUES ('{}', {})".format(name, age) try: cursor.execute(sql) db.commit() except: db.rollback() finally: db.close() # 輸出HTTP頭部 print("Content-type:text/html") print() # 輸出頁面內容 print("<html><head><title>CGI Program</title></head>") print("<body>") print("<h2>Insert success</h2>") print("</body>") print("</html>")
在上面的示例中,我們先是向 MySQL 中插入了用戶提交的數據。然後輸出了插入成功的提示信息。
四、使用模板引擎
使用模板引擎可以將網頁內容和編寫邏輯代碼分離,使得代碼更加清晰易懂。
Python中有很多優秀的模板引擎,比如 Jinja2、Mako、Chameleon等等。下面我們以 Jinja2 為例,編寫一個簡單的網頁模板:
<!DOCTYPE html> <html> <head> <title>{{ title }}</title> </head> <body> <h1>{{ title }}</h1> <form method="POST"> <input type="text" name="name" placeholder="Name"> <br><br> <input type="number" name="age" placeholder="Age"> <br><br> <input type="submit" value="Submit"> </form> </body> </html>
接著,編寫一個使用 Jinja2 渲染網頁的 CGI 腳本:
#!/usr/bin/python # coding=utf8 import cgi from jinja2 import Template # 獲取表單數據 form = cgi.FieldStorage() name = form.getvalue("name") age = form.getvalue("age") # 渲染模板文件 template = Template(open('./template.html').read()) html = template.render(title='CGI Program') # 輸出HTTP頭部 print("Content-type:text/html") print() # 輸出渲染後的頁面內容 print(html)
實際上,使用模板引擎的優勢還要更多,包括表單驗證、模板繼承、宏等等。這些可以在熟悉模板引擎之後自行探究。
五、使用CGI腳本創建簡單的Web應用
通過前面的介紹,我們可以發現使用 Python 編寫 CGI 腳本非常簡單。接下來,我們可以通過組合使用既有的 CGI 腳本(比如獲取表單數據、與資料庫交互、渲染模板文件等),來創建一個簡單的 Web 應用。
下面我們來實現一個簡單的註冊功能。用戶在註冊頁面中輸入用戶名和年齡,我們將這些信息插入到資料庫中。註冊成功後,再跳轉到歡迎頁面,顯示註冊的用戶列表。
首先,我們需要編寫一個表單頁面:
<!DOCTYPE html> <html> <head> <title>Register</title> </head> <body> <h1>Register</h1> <form method="POST" action="/cgi-bin/register.py"> <input type="text" name="name" placeholder="Name"> <br><br> <input type="number" name="age" placeholder="Age"> <br><br> <input type="submit" value="Submit"> </form> </body> </html>
接著,我們需要編寫一個註冊表單提交後的處理腳本:
#!/usr/bin/python # coding=utf8 import cgi import MySQLdb import cgitb # 輸出cgi信息到瀏覽器 cgitb.enable() # 連接資料庫 db = MySQLdb.connect("localhost", "root", "password", "test") # 獲取表單數據 form = cgi.FieldStorage() name = form.getvalue('name') age = form.getvalue('age') # 插入數據 cursor = db.cursor() sql = "INSERT INTO user(name, age) VALUES ('{}', {})".format(name, age) try: cursor.execute(sql) db.commit() except: db.rollback() finally: db.close() # 跳轉頁面 print("Location:/cgi-bin/welcome.py") print()
在這個處理腳本中,我們首先使用 cgitb 模塊,使得程序出錯時的信息能夠輸出到瀏覽器。然後,我們連接資料庫,獲取表單數據,插入到資料庫中。最後,使用 HTTP 頭部指示瀏覽器跳轉到 welcome.py 頁面。
下面是 welcome.py 頁面的代碼:
#!/usr/bin/python # coding=utf8 import cgi import MySQLdb import cgitb from jinja2 import Template # 輸出cgi信息到瀏覽器 cgitb.enable() # 連接資料庫 db = MySQLdb.connect("localhost", "root", "password", "test") # 查詢數據 cursor = db.cursor() sql = "SELECT * FROM user" cursor.execute(sql) result = cursor.fetchall() # 渲染模板 template = Template(open('./template.html').read()) html = template.render(title='Welcome', result=result) # 輸出http頭部 print("Content-Type: text/html") print() # 輸出渲染後的頁面內容 print(html)
我們在這個腳本中使用了 Jinja2 模板引擎,渲染了模板文件,並從資料庫中查詢到了用戶信息,並將其傳遞給模板文件。最後,輸出渲染後的頁面內容。
使用上面三個腳本,我們創建了一個簡單的註冊功能。通過組合和修改這三個腳本,我們還可以完成很多其他的 Web 應用。
原創文章,作者:QVHE,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/143653.html