I have a python CGI script that receives a POST request containing a specific HTTP header. How do you read and parse the headers received? I am not using BaseHTTPRequestHandler
or HTTPServer
. I receive the body of the post with sys.stdin.read()
. Thanks.
Asked
Active
Viewed 5,857 times
6

Alec Fenichel
- 1,257
- 1
- 13
- 27
2 Answers
5
It is possible to get a custom request header's value in an apache CGI script with python. The solution is similar to this.
Apache's mod_cgi will set environment variables for each HTTP request header received, the variables set in this manner will all have an HTTP_
prefix, so for example x-client-version: 1.2.3
will be available as variable HTTP_X_CLIENT_VERSION
.
So, to read the above custom header just call os.environ["HTTP_X_CLIENT_VERSION"]
.
The below script will print all HTTP_*
headers and values:
#!/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>"

Community
- 1
- 1

André Fernandes
- 2,335
- 3
- 25
- 33
0
You might want to look at the cgi module included with Python's standard library. It appears to have a cgi.parse_header(string) function that you might find to be helpful in trying to get the headers.

Noctis Skytower
- 21,433
- 16
- 79
- 117
-
cgi.parse_header('X-GitHub-Event') doesn't return the header. It doesn't return any header I have tried. – Alec Fenichel Aug 02 '15 at 20:30
-
@AlecFenichel I believe its purpose is to parse the headers after you have gotten them. – Noctis Skytower Aug 03 '15 at 22:02
-
6Yes. But how do you get them? – Alec Fenichel Aug 05 '15 at 16:37
-
This does nothing. You can't parse a header if you haven't even gotten them. – pigeonburger Apr 06 '21 at 04:43