Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read all HTTP headers in Python CGI script?

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.

like image 489
Alec Fenichel Avatar asked Jul 31 '15 16:07

Alec Fenichel


People also ask

What are HTTP headers used in CGI programs?

The first line of output for most CGI programs must be an HTTP header that tells the client Web browser what type of output it is sending back via STDOUT. Only scripts that are called from a server-side include are exempt from this requirement. All HTTP headers must be followed by a blank line.

How do I read HTTP headers?

To view the request or response HTTP headers in Google Chrome, take the following steps : In Chrome, visit a URL, right click , select Inspect to open the developer tools. Select Network tab. Reload the page, select any HTTP request on the left panel, and the HTTP headers will be displayed on the right panel.

What is CGI FieldStorage?

FieldStorage. getlist (name) This method always returns a list of values associated with form field name. The method returns an empty list if no such form field or value exists for name. It returns a list consisting of one item if only one such value exists.


1 Answers

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>"
like image 112
André Fernandes Avatar answered Nov 01 '22 13:11

André Fernandes