Question

How can I find out the http request my python cgi received? I need different behaviors for HEAD and GET.

Thanks!

Was it helpful?

Solution

import os

if os.environ['REQUEST_METHOD'] == 'GET':
    # blah

OTHER TIPS

This is not a direct answer to your question. But your question stems from doing things the wrong way.

Do not write Python CGI scripts.

Write a mod_wsgi application. Better still, use a Python web framework. There are dozens. Choose one like Werkzeug.

The WSGI standard (described in PEP 333) makes it much, much easier to find things in the web request.

The mod_wsgi implementation is faster and more secure than a CGI.

A web framework is also simpler than writing your own CGI script or mod_wsgi application.

Why do you need to distinguish between GET and HEAD?

Normally you shouldn't distinguish and should treat a HEAD request just like a GET. This is because a HEAD request is meant to return the exact same headers as a GET. The only difference is there will be no response content. Just because there is no response content though doesn't mean you no longer have to return a valid Content-Length header, or other headers, which are dependent on the response content.

In mod_wsgi, which various people are pointing you at, it will actually deliberately change the request method from HEAD to GET in certain cases to guard against people who wrongly treat HEAD differently. The specific case where this is done is where an Apache output filter is registered. The reason that it is done in this case is because the output filter may expect to see the response content and from that generate additional response headers. If you were to decide not to bother to generate any response content for a HEAD request, you will deprive the output filter of the content and the headers they add may then not agree with what would be returned from a GET request. The end result of this is that you can stuff up caches and the operation of the browser.

The same can apply equally for CGI scripts behind Apache as output filters can still be added in that case as well. For CGI scripts there is nothing in place though to protect against users being stupid and doing things differently for a HEAD request.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top