1. Technology

Testing CGI With Python

By

4 of 4

Getting the CGI Environment Variables

In the case of Apache, you get output similar to the following:

DOCUMENT_ROOT: /var/www
GATEWAY_INTERFACE: CGI/1.1
HTTP_ACCEPT: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
HTTP_ACCEPT_CHARSET: ISO-8859-1,utf-8;q=0.7,*;q=0.7
HTTP_ACCEPT_ENCODING: gzip,deflate
HTTP_ACCEPT_LANGUAGE: en-gb,en;q=0.5
HTTP_CACHE_CONTROL: max-age=0
HTTP_CONNECTION: keep-alive
HTTP_HOST: 192.168.0.2
HTTP_KEEP_ALIVE: 300
HTTP_USER_AGENT: Mozilla/5.0 (X11; U; Linux i686; en-GB; rv:1.8.0.11) Gecko/20070327 Ubuntu/dapper-security Firefox/1.5.0.11
PATH: /usr/local/bin:/usr/bin:/bin
QUERY_STRING:
REMOTE_ADDR: 192.168.0.2
REMOTE_PORT: 46164
REQUEST_METHOD: GET
REQUEST_URI: /~al/About.com_Playground/test_cgi.cgi
SCRIPT_FILENAME: /home/al/public_html/About.com_Playground/test_cgi.cgi
SCRIPT_NAME: /~al/About.com_Playground/test_cgi.cgi
SERVER_ADDR: 192.168.0.2
SERVER_ADMIN: webmaster@localhost
SERVER_NAME: 192.168.0.2
SERVER_PORT: 80
SERVER_PROTOCOL: HTTP/1.1
SERVER_SIGNATURE: <address>Apache/2.0.55 (Ubuntu) mod_jk/1.2.14 mod_python/3.1.4 Python/2.4.3 PHP/5.1.2 Server at 192.168.0.2 Port 80</address>
SERVER_SOFTWARE: Apache/2.0.55 (Ubuntu) mod_jk/1.2.14 mod_python/3.1.4 Python/2.4.3 PHP/5.1.2

This for-loop will work on Python 2.4 and later. If it does not work for you, you may find that your Python installation needs updating. In the meantime, you can substitute these three lines for the one beginning "for k in...":

 keys = os.environ.keys() 
 keys.sort() 
 for k in keys: 

With either for-loop, you will get the same output. The result will be a small Python CGI script that you can use anywhere to figure out the environment in which you are programming. I should note in closing that parts of this tutorial were inspired by the coding of Jeff Bauer and Carey Evans and their script of a similar nature.

  1. About.com
  2. Technology
  3. Python
  4. Web Development
  5. Testing CGI With Python: Getting the CGI Environment Variables

©2014 About.com. All rights reserved.