公共网关接口 (CGI) 允许在 HTTP 服务器上执行一些 Python 程序。

安装

默认情况下,在 HTTP 中打开一个 .py 文件会返回其内容。为了使服务器编译并执行源代码,必须将其放在包含 .htaccess 文件的目录中,该文件包含以下行:

AddHandler cgi-script .py
Options +ExecCGI

注意:在 Unix 服务器上,文件默认情况下不可执行,因此必须使用以下命令进行设置:chmod +x *.py

示例

模块 cgitb 用于调试:

Python
#!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

对于 MySQL 数据库,需要 import MySQLdb

以下文件名为 CGI_MySQL.py,同时使用了这两个模块

Python
#!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>"
Last modified: Friday, 31 January 2025, 1:32 AM