Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

Python Programming/CGI interface

From Wikibooks, open books for an open world
<Python Programming
Previous: GUI ProgrammingIndexNext: WSGI web programming


TheCommon 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 .pyOptions +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 modulecgitb 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>"importcgitbcgitb.enable()importosprint"The CGI file is located into:"printos.path.dirname(__file__)print"</body></html>"

The usage of a form needs animport cgi[2].

For aMySQL database, itsimport MySQLdb[3].

The following file is calledCGI_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>"importcgitbcgitb.enable()importcgi,MySQLdbform=cgi.FieldStorage()ifform.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')+"'")forrowincursor.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
Previous: GUI ProgrammingIndexNext: WSGI web programming
Retrieved from "https://en.wikibooks.org/w/index.php?title=Python_Programming/CGI_interface&oldid=3678047"
Category:

[8]ページ先頭

©2009-2025 Movatter.jp