Jump to content

Python Programming/CGI interface

From Wikibooks, open books for an open world


The Common Gateway Interface (CGI) allows to execute some Python programs on an HTTP server.

Installation

[edit | edit source]

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 lines[1]:

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

[edit | edit source]

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 cgi[2].

For a MySQL database, its import MySQLdb[3].

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

[edit | edit source]
  1. "HOWTO Use Python in the web".
  2. http://fr.openclassrooms.com/informatique/cours/apercu-de-la-cgi-avec-python
  3. https://pypi.python.org/pypi/MySQL-python/1.2.5