How do I read all HTTP headers in a Python CGI script?

I have a CGI python script that receives a POST request containing a specific HTTP header. How do you read and parse the headers received? I don't use BaseHTTPRequestHandler

or HTTPServer

. I am getting the body of the message with sys.stdin.read()

. Thank.

+3


source to share


2 answers


In the header of an apache CGI script with python, you can get the value of the custom request header. The solution is similar to this .

Apache mod_cgi will set environment variables for every HTTP request header received, variables set this way will be prefixed HTTP_

, so for example x-client-version: 1.2.3

will be available as a variable HTTP_X_CLIENT_VERSION

.

So, to read the above custom header just call os.environ["HTTP_X_CLIENT_VERSION"]

.



Below script will print all headers and values HTTP_*

:

#!/usr/bin/env python

import os

print "Content-Type: text/html"
print "Cache-Control: no-cache"
print

print "<html><body>"
for headername, headervalue in os.environ.iteritems():
    if headername.startswith("HTTP_"):
        print "<p>{0} = {1}</p>".format(headername, headervalue)


print "</html></body>"

      

+3


source


You might want to look at the cgi module included in the Python standard library. It seems to have a cgi.parse_header (string) function that might be helpful when trying to get headers.



0


source







All Articles