411 REFERENCE · Wikibooks
Python Programming/CGI interface
Reference material by Wikibooks contributors. This retains its source identity and is not 411 news reporting.
GUI Programming WSGI web programming
The Common Gateway Interface (CGI) allows to execute some Python programs on an HTTP server.
Installation
By default, open a .py file in HTTP returns its content. In order to make the server compile and execute the source code, it must be placed in a directory including an .htaccess file, with the lineshttp://docs.python.org/howto/webservers.html en HOWTO Use Python in the web:
AddHandler cgi-script .py
Options +ExecCGI
Attention: on the Unix-like servers the files aren't executable by default, so this must be set with the command: chmod +x *.py.
Examples
The module cgitb is used for debugging:
#!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>"
The usage of a form needs an import cgihttp://fr.openclassrooms.com/informatique/cours/apercu-de-la-cgi-avec-python.
For a MySQL database, its import MySQLdbhttps://pypi.python.org/pypi/MySQL-python/1.2.5.
The following file is called CGI_MySQL.py, and uses the both modules:
#!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>"
References
GUI Programming WSGI web programming
fr:Programmation Python/L'interface CGI