views:

23

answers:

1

HTTP HEAD requests should contain the Content-Length header as if they were GET requests. But if I set a Content-Length header it gets overridden by the WSGI environment (discussion related to mod_wsgi).

Take a look at the following example:

from wsgiref.simple_server import make_server

def application(environ, start_response):
    status = '200 OK'
    headers = [('Content-Type', 'text/plain'), ('Content-Length', '77')]
    start_response(status, headers)
    return []

httpd = make_server('', 8000, application)
print("Serving on port 8000...")
httpd.serve_forever()

... and then calling it with curl:

$ curl -X HEAD http://localhost:8000/ -i
HTTP/1.0 200 OK
Date: Mon, 04 Oct 2010 16:02:27 GMT
Server: WSGIServer/0.1 Python/2.7
Content-Type: text/plain
Content-Length: 0                         <-- should be 77

How can I tell the WSGI environment not to override the content length value?

A: 

There is no such configuration setting. You have to override or modify wsgiref/handlers.py, like this:

from wsgiref.simple_server import make_server
from wsgiref.simple_server import ServerHandler
def finish_content(self):
    """Ensure headers and content have both been sent"""
    if not self.headers_sent:
        if (self.environ.get('REQUEST_METHOD', '') != 'HEAD' or
            'Content-Length' not in self.headers):
            self.headers['Content-Length'] = 0
        self.send_headers()
ServerHandler.finish_content = finish_content
def application(environ, start_response):
    status = '200 OK'
    headers = [('Content-Type', 'text/plain'), ('Content-Length', '77')]
    start_response(status, headers)
    return []
httpd = make_server('', 8000, application)
print("Serving on port 8000...")
httpd.serve_forever()
pts