Cette page présente un petit exemple de CGI fait en Python. L'exemple choisi ici est un outil de tests réseau à distance réalisé à l'occasion d'un problème de routage chez le FAI qu'il ne constatait pas depuis son propre réseau. Cet exemple montre comment faire un CGI rapidement pour un besoin ponctuel, en Python pur sans autre dépendance (pas de Django ou autre Pylons ici). Fichier `/usr/lib/cgi-bin/network-test.py` : {{{#!python #!/usr/bin/env python # -*- coding: utf-8 -*- """ Network test tools (CGI) Copyright ©2009 Agence universitaire de la Francophonie Licence: GNU General Public License, version 2 Author: Progfou Creation: 2009-03-21 Debian-Depends: mtr-tiny iputils-ping dnsutils Filename: /usr/lib/cgi-bin/network-test.py (chmod +x) Usage: http://localhost/cgi-bin/network-test.py """ import os import cgi import commands ACTIONS = { 'mtr': u"mtr -rc%(count)s %(addr)s", 'ping': u"ping -nc%(count)s %(addr)s", 'host': u"host %(addr)s", 'dig': u"dig any %(addr)s", 'dig +trace': u"dig any +trace %(addr)s", 'dig +nssearch': u"dig +nssearch %(addr)s", 'source': u"cat %(__file__)s", } COUNT = 3 HTML = u""" %(title)s

%(title)s

%(content)s
%(signature)s """ TITLE = u"""Network test tools @ %(HTTP_HOST)s[%(SERVER_ADDR)s]""" REQUEST = u"""
Request

(You'll have to wait about %(count)s seconds after clic for result to display.)
""" ERROR = u"""
Error %(content)s
""" RESULT = u"""
Result%(legend_ext)s
%(content)s
""" SIGNATURE = u"""
Copyright ©2009  Agence universitaire de la Francophonie
http://www.auf.org/regions/asie-pacifique/
(view this script source)
""" if __name__ == "__main__": query_string = cgi.parse_qs(os.environ['QUERY_STRING']) addr = query_string.get('addr', ["www.auf.org"])[0] count = query_string.get('count', [COUNT])[0] result_legend_ext = "" error = None result = None # check URL parameters if not addr.replace('.','').replace('-','').isalnum(): error = u"Invalid address!" addr = "invalid" elif type(count) == str and not count.isdigit(): error = u"Invalid count!" count = COUNT else: # process request action = query_string.get('action', [None])[0] if action in ACTIONS: command = (ACTIONS[action] % locals()).encode('utf-8') (status, result) = commands.getstatusoutput(command) result = result.decode('utf-8', 'ignore') result_legend_ext = u" for `%s`" % command elif action is not None: error = u"Invalid action!" # display result print u"Content-Type: text/html; charset=utf-8\n" #cgi.print_environ() title = TITLE % os.environ content = REQUEST % locals() if error is not None: content += ERROR % {'content': cgi.escape(error)} if result is not None: content += RESULT % {'content': cgi.escape(result), 'legend_ext': result_legend_ext} signature = SIGNATURE % locals() print (HTML % locals()).encode('utf-8') }}} Exemple d'utilisation : http://smtp.vn.auf.org/cgi-bin/network-test.py ----