1
# Copyright (C) 2011 Canonical Ltd.
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
"""WSGI apps tend to return body content as part of a HEAD request.
19
We should definitely not do that.
22
class HeadMiddleware(object):
23
"""When we get a HEAD request, we should not return body content.
25
WSGI defaults to just generating everything, and not paying attention to
26
whether it is a GET or a HEAD request. It does that because of potential
27
issues getting the Headers correct.
29
This middleware works by just omitting the body if the request method is
33
def __init__(self, app):
34
self._wrapped_app = app
35
self._real_environ = None
36
self._real_start_response = None
37
self._real_writer = None
39
def noop_write(self, chunk):
40
"""We intentionally ignore all body content that is returned."""
43
def start_response(self, status, response_headers, exc_info=None):
45
self._real_writer = self._real_start_response(status,
48
self._real_writer = self._real_start_response(status,
49
response_headers, exc_info)
50
return self.noop_write
52
def __call__(self, environ, start_response):
53
self._real_environ = environ
54
self._real_start_response = start_response
55
if environ.get('REQUEST_METHOD', 'GET') == 'HEAD':
56
result = self._wrapped_app(environ, self.start_response)
60
result = self._wrapped_app(environ, start_response)