background preloader

Python CGI

Facebook Twitter

Documentation and Tutorials to implement Python CGI

Tutoriel Apache : Contenu dynamique basé sur CGI - Serveur Apache HTTP Version 2.4. Introduction The CGI (Common Gateway Interface) defines a way for a web server to interact with external content-generating programs, which are often referred to as CGI programs or CGI scripts. It is the simplest, and most common, way to put dynamic content on your web site. This document will be an introduction to setting up CGI on your Apache web server, and getting started writing CGI programs. Configuring Apache to permit CGI In order to get your CGI programs to work properly, you'll need to have Apache configured to permit CGI execution. There are several ways to do this. Note: If Apache has been built with shared module support you need to ensure that the module is loaded; in your httpd.conf you need to make sure the LoadModule directive has not been commented out.

LoadModule cgi_module modules/mod_cgi.so ScriptAlias The ScriptAlias directive tells Apache that a particular directory is set aside for CGI programs. The ScriptAlias directive looks like: AddHandler cgi-script .cgi .pl #! #! #! File Upload | Web Python. The python scripts in this page and in the next one will try to save an uploaded file in a directory named files in the directory where it is running. If the directory where the script is running is /path/to/dir then the /path/to/dir/files directory must exist. If it does not it will fail. To upload a file the HTML form must have the enctype attribute set to multipart/form-data.

The input tag with the file type will create a "Browse" button. <html><body><form enctype="multipart/form-data" action="save_file.py" method="post"><p>File: <input type="file" name="file"></p><p><input type="submit" value="Upload"></p></form></body></html> The getfirst() and getlist() methods will only return the file(s) content. . #! A directory traversal attack is one where the attacker submits a file with a leading path like in ../.. Apprendre à programmer avec Python/Applications web. Un livre de Wikilivres. Vous avez certainement déjà appris par ailleurs un grand nombre de choses concernant la rédaction de pages web. Vous savez que ces pages sont des documents au format HTML, que l'on peut consulter via un réseau (intranet ou internet) à l'aide d'un logiciel appelé browser web ou navigateur (Netscape, Konqueror, Internet explorer, ...).

Les pages HTML sont installées dans les répertoires publics d'un autre ordinateur où fonctionne en permanence un logiciel appelé serveur Web (Apache, IIS, Zope, ...). Lorsqu'une connexion a été établie entre cet ordinateur et le vôtre, votre logiciel navigateur peut dialoguer avec le logiciel serveur (par l'intermédiaire de toute une série de dispositifs matériels et logiciels dont nous ne traiterons pas ici : lignes téléphoniques, routeurs, caches, protocoles de communication ...).

Le protocole HTTP qui gère la transmission des pages web autorise l'échange de données dans les deux sens. L'interface CGI[modifier | modifier le wikicode] Apprendre à programmer avec Python. Vous avez certainement déjà appris par ailleurs un grand nombre de choses concernant la rédaction de pages web. Vous savez que ces pages sont des documents au format HTML, que l'on peut consulter via un réseau (intranet ou internet) à l'aide d'un logiciel appelé browser web ou navigateur (Netscape, Konqueror, Internet explorer, ...).

Les pages HTML sont installées dans les répertoires publics d'un autre ordinateur où fonctionne en permanence un logiciel appelé serveur Web (Apache, IIS, Zope, ...). Lorsqu'une connexion a été établie entre cet ordinateur et le vôtre, votre logiciel navigateur peut dialoguer avec le logiciel serveur (par l'intermédiaire de toute une série de dispositifs matériels et logiciels dont nous ne traiterons pas ici : lignes téléphoniques, routeurs, caches, protocoles de communication ...). Le protocole HTTP qui gère la transmission des pages web autorise l'échange de données dans les deux sens. 17.2.1. Une interaction CGI rudimentaire▲ 1. 17.2.2. 17.2.3. 17.1. Common Gateway Interface. Un article de Wikipédia, l'encyclopédie libre. Principe de fonctionnement[modifier | modifier le code] Du point de vue du serveur HTTP, il est nécessaire de le configurer pour associer l'exécution du programme CGI à certaines URL.

Par défaut, les serveurs se contentent généralement de retourner le contenu des fichiers. Limitations et évolutions[modifier | modifier le code] Une autre solution est d'intégrer le programme directement dans le serveur HTTP sous forme de module, ceci nécessitant une adaptation bien plus lourde et qui est propre au serveur HTTP. C'est le cas avec Apache qui propose des dizaines de modules pour interpréter des langages, se connecter à des bases de données, etc. Historique[modifier | modifier le code] L'interface CGI existe depuis 1993.

Exemple d'utilisation[modifier | modifier le code] Un exemple de programme CGI est celui qui fait fonctionner l'annuaire web Open Directory Project. Notes et références[modifier | modifier le code] Bottle: Python Web Framework — Bottle 0.13-dev documentation. Bottle is a fast, simple and lightweight WSGI micro web-framework for Python. It is distributed as a single file module and has no dependencies other than the Python Standard Library. Routing: Requests to function-call mapping with support for clean and dynamic URLs.Templates: Fast and pythonic built-in template engine and support for mako, jinja2 and cheetah templates.Utilities: Convenient access to form data, file uploads, cookies, headers and other HTTP-related metadata.Server: Built-in HTTP development server and support for paste, fapws3, bjoern, gae, cherrypy or any other WSGI capable HTTP server. Example: “Hello World” in a bottle from bottle import route, run, template @route('/hello/<name>')def index(name): return template('<b>Hello {{name}}</b>!

' Run this script or paste it into a Python console, then point your browser to Download and Install User’s Guide Start here if you want to learn how to use the bottle framework for web development. License. Tech Tip: Really Simple HTTP Server with Python. If you need a quick web server running and you don't want to mess with setting up apache or something similar, then Python can help. Python comes with a simple builtin HTTP server. With the help of this little HTTP server you can turn any directory in your system into your web server directory. The only thing you need to have installed is Python. Practically speaking this is very useful to share files inside your local network. Implementing this tiny but hugely useful HTTP server is very simple, its just a single line command.

Assume that I would like to share the directory /home/hisam and my IP address is 192.168.1.2 Open up a terminal and type: $ cd /home/somedir $ python -m SimpleHTTPServer That's it! Serving HTTP on 0.0.0.0 port 8000 ... Now open a browser and type the following address: You can also access it via: If the directory has a file named index.html, that file will be served as the initial file. If you wish to change the port that's used start the program via: Développer une WebApp en Python. Objectifs du tutoriel: Apprendre les bases de Python au travers d’un projet pluridisciplinaire. Dans ce projet, je vous propose de développer de A à Z une application Web client/serveur basée sur une architecture Model2 structurée comme un MVC. Les points suivants sont abordés: Principe d’une WebApp (application Web) avec PythonConception Orientée Objet (Model2 et MVC)Utilisation (souvent basique) de quelques modules de la PSL (Python Standard Library) : Expression régulièresLecture/Écriture dans des fichiersBases de données Sqlite3Serveur Web httpSérialisationRequêtes httpModule cgi (Common Gateway Interface)Tests unitairesThreadsNotions de Javascript et de HTML Template HTML et CSSUtilisation de jQueryUI (le widget datepicker)Manipulation de l’API Highcharts en javascript pour l’affichage de graphiques Cahier des charges: Le tutoriel peut être réalisé en local sans même disposer d’un serveur Web (par exemple Apache est inutile pour ce tuto), ceci sur n’importe quel OS.

Code source. Python CGI: An Interactive Instruction. Aperçu de la CGI avec Python. 20.2. cgi — Common Gateway Interface support — Python v2.7.8 documentation. Source code: Lib/cgi.py Support module for Common Gateway Interface (CGI) scripts. This module defines a number of utilities for use by CGI scripts written in Python. 20.2.1. Introduction A CGI script is invoked by an HTTP server, usually to process user input submitted through an HTML <FORM> or <ISINDEX> element. Most often, CGI scripts live in the server’s special cgi-bin directory. The script’s input is connected to the client too, and sometimes the form data is read this way; at other times the form data is passed via the “query string” part of the URL. The output of a CGI script should consist of two sections, separated by a blank line.

Print "Content-Type: text/html" # HTML is followingprint # blank line, end of headers The second section is usually HTML, which allows the client software to display nicely formatted text with header, in-line images, etc. Print "<TITLE>CGI script output</TITLE>"print "<H1>This is my first CGI script</H1>"print "Hello, world!

" 20.2.2. 20.2.3. 20.2.4. Python CGI Programming. What is CGI? The Common Gateway Interface, or CGI, is a set of standards that define how information is exchanged between the web server and a custom script.The CGI specs are currently maintained by the NCSA and NCSA defines CGI is as follows:The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers. The current version is CGI/1.1 and CGI/1.2 is under progress. Web Browsing To understand the concept of CGI, lets see what happens when we click a hyper link to browse a particular web page or URL. Your browser contacts the HTTP web server and demands for the URL i.e., filename.Web Server will parse the URL and will look for the filename in if it finds that file then sends it back to the browser, otherwise sends an error message indicating that you have requested a wrong file.Web browser takes response from web server and displays either the received file or error message.

CGI Architecture Diagram #! HTTP Header #! Programmation Python/Programmer en deux minutes/un serveur Web. Un livre de Wikilivres. 0. Pour programmer un serveur Web en deux minutes, nous allons écrire un script en Python et l'exécuter dans une console. Le programme va utiliser deux ensemble d'instructions, ces ensembles étant définis dans la bibliothèque de base. Serveur HTTP[modifier | modifier le wikicode] 1. Ouvrir un éditeur de texte, écrire le script... ...enregistrez ce script (par exemple serveur_http.py) dans un répertoire que vous voulez partager (par exemple /PUBLIC_web) et exécutez-le dans une console.

Félicitation, votre programme répond aux requêtes [Note 1] et votre répertoire public[Note 2] peut être téléchargé. Aller ↑ « » est une requête de protocole HTTP à votre machine locale via le port 5432Aller ↑ Nommé « /PUBLIC_web » dans l'exemple Index.html[modifier | modifier le wikicode] 2. ...enregistrez ce fichier sous le nom index.html dans le répertoire que vous partagez (Nommé « /PUBLIC_web » dans cet exemple). Ug's HTML & Python CGI pages: CGI scripts. Test.py This was my first Python CGI script. It lists some information about its execution environment, such as environment variables, current directory, userid etc. Try out test.py. Look at test.py. show.py This script is used to display other scripts. It prints out the source code and creates links to imported modules or to documentation pages of standard modules.

Arguments: Try out show.py: Look at show.py. form.py This is a test script that I use mainly in my HTML forms page but it can be used by anyone interested in seeing how script arguments are transferred and interpreted. Try out form.py: Look at form.py. cookie.py This is a small sample script to show how you can use the Python Cookie module. Take a look a the script, run it a few times and look at the results. Try out cookie.py. Look at cookie.py.

For some time, I kept my own copy of the Cookie module on this server; long after it was brought into the Python release. Ripurl.py Look at ripurl.py. debug.py ... Look at debug.py. Running a Simple CGI Web Server. To learn CGI (Common Gateway Interface) programming in Python, you need access to a web server configured for handling Python CGI requests. For learning purposes or debugging you may run the web servers that come with Python. If you want to just start up the most basic CGI web server, open a console window and change to the directory from which you want to run the server. You will need to have a sub-directory called cgi-bin within this directory. To run a simple test, copy the file hello.py into that directory. Then start Python as follows: python -m CGIHTTPServer where the -m option (to run a library module as a script) is new in version 2.4. C:\classes\python>python -m CGIHTTPServer Serving HTTP on 0.0.0.0 port 8000 ...

Note that the console window is now running the server and is not available for further interaction. Next activate the following link: Your browser window should look something like this:

WSGI

Hickford/MechanicalSoup.