跳轉到內容

Python 程式設計/CGI 介面

來自 Wikibooks,開放世界中的開放書籍


通用閘道器介面 (CGI) 允許在 HTTP 伺服器上執行一些 Python 程式。

預設情況下,在 HTTP 中開啟 .py 檔案會返回其內容。為了使伺服器編譯並執行原始碼,它必須放置在一個包含 .htaccess 檔案的目錄中,其中包含以下行[1]

AddHandler cgi-script .py
Options +ExecCGI

注意:在類 Unix 伺服器上,檔案預設不可執行,因此必須使用以下命令設定:chmod +x *.py

cgitb 模組用於除錯

#!C:\Program Files (x86)\Python\python.exe
# -*- coding: UTF-8 -*-
print "Content-type: text/html; charset=utf-8\n\n"
print "<html><head><title>Local directory</title></head><body>"
import cgitb
cgitb.enable()
import os
print "The CGI file is located into:"
print os.path.dirname(__file__)
print "</body></html>"

表單的使用需要 import cgi[2]

對於 MySQL 資料庫,需要 import MySQLdb[3]

以下檔名為 CGI_MySQL.py,並使用這兩個模組

#!C:\Program Files (x86)\Python\python.exe
# -*- coding: UTF-8 -*-
print "Content-type: text/html; charset=utf-8\n\n"
print "<html><head><title>DB CGI</title></head><body>"
print "<h1>MySQL extraction</h1>"
print "<ul>"
import cgitb
cgitb.enable()
import cgi, MySQLdb
form = cgi.FieldStorage()
if form.getvalue('name') == None:
	print "<h2>Research a name</h2>"
	print '''
	<form action="CGI_MySQL.py" method="post">
	<input type="text" name="name" />
	<input type="submit"></form>
		'''
else:
	print "<h2>Result</h2>"
	print "List for " + form.getvalue('name') + " :"
	connection = MySQLdb.connect(user='login1', passwd='passwd1', db='base1')
	cursor = connection.cursor()
	cursor.execute("SELECT page_title FROM page WHERE name ='"+form.getvalue('name')+"'")
	for row in cursor.fetchall():
		print "<li>%s</li>" % row[0]
	connection.close()
print "</ul>"
print "</body></html>"

參考文獻

[編輯 | 編輯原始碼]
  1. "如何在 Web 中使用 Python".
  2. http://fr.openclassrooms.com/informatique/cours/apercu-de-la-cgi-avec-python
  3. https://pypi.python.org/pypi/MySQL-python/1.2.5
華夏公益教科書