views:

51

answers:

3

I'm writing a very simple web service, written in Python and run as CGI on an Apache server.

According to Python docs (somewhere... I forgot where), I can use sys.stdin to read the data POSTed by a random client, and this has been working fine. However, I would like to be able to read the HTTP header information as well - incoming IP, user agent, and so on. I'd also like to keep it very simple for now, by using only Python libraries (so no mod-python). How do I do this?

A: 

As this page explains, most HTTP request headers are made available to your CGI script via environment variables. Run cgi.test() instead of your script to see the environment (including HTTP request headers) shown back to your visiting browser.

Alex Martelli
A: 

These are given to the CGI script through the environment:

import os
user_agent = os.environ["HTTP_USER_AGENT"]
ip = os.environ["REMOTE_ADDR"]
balpha
+1  A: 

If you are running as a CGI, you can't read the HTTP header directly, but the web server put much of that information into environment variables for you. You can just pick it out of os.environ[]

The list of environment variables that might be there is pretty long. You can find it by doing a web search for "common gateway interface". For example, in http://www.ietf.org/rfc/rfc3875.txt they are called "meta-variables".

sienkiew
Thank you! That was exactly what I needed.
jawonlee