How do I read all HTTP headers in a Python CGI script?
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>"
source to share
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.
source to share