Code

Ticket #2131: httpresponsesendfile-no-default-content_bypass-middleware.1.diff

File httpresponsesendfile-no-default-content_bypass-middleware.1.diff, 7.0 KB (added by mrts, 5 years ago)

Fix method naming typo

Line 
1Index: django/http/__init__.py
2===================================================================
3--- django/http/__init__.py     (revision 10054)
4+++ django/http/__init__.py     (working copy)
5@@ -393,6 +393,20 @@
6             raise Exception("This %s instance cannot tell its position" % self.__class__)
7         return sum([len(chunk) for chunk in self._container])
8 
9+class HttpResponseSendFile(HttpResponse):
10+    def __init__(self, path_to_file, content_type=None, block_size=8192):
11+        if not content_type:
12+            from mimetypes import guess_type
13+            content_type = guess_type(path_to_file)[0]
14+            if content_type is None:
15+                content_type = "application/octet-stream"
16+        super(HttpResponseSendFile, self).__init__(None,
17+                content_type=content_type)
18+        self.sendfile_filename = path_to_file
19+        self.block_size = block_size
20+        self._headers['content-length'] = ('Content-Length',
21+                os.path.getsize(path_to_file))
22+
23 class HttpResponseRedirect(HttpResponse):
24     status_code = 302
25 
26Index: django/core/servers/basehttp.py
27===================================================================
28--- django/core/servers/basehttp.py     (revision 10054)
29+++ django/core/servers/basehttp.py     (working copy)
30@@ -313,10 +313,9 @@
31         in the event loop to iterate over the data, and to call
32         'self.close()' once the response is finished.
33         """
34-        if not self.result_is_file() and not self.sendfile():
35-            for data in self.result:
36-                self.write(data)
37-            self.finish_content()
38+        for data in self.result:
39+            self.write(data)
40+        self.finish_content()
41         self.close()
42 
43     def get_scheme(self):
44Index: django/core/handlers/wsgi.py
45===================================================================
46--- django/core/handlers/wsgi.py        (revision 10054)
47+++ django/core/handlers/wsgi.py        (working copy)
48@@ -231,30 +231,30 @@
49             self.initLock.release()
50 
51         set_script_prefix(base.get_script_name(environ))
52-        signals.request_started.send(sender=self.__class__)
53-        try:
54-            try:
55-                request = self.request_class(environ)
56-            except UnicodeDecodeError:
57-                response = http.HttpResponseBadRequest()
58-            else:
59-                response = self.get_response(request)
60 
61-                # Apply response middleware
62-                for middleware_method in self._response_middleware:
63-                    response = middleware_method(request, response)
64-                response = self.apply_response_fixes(request, response)
65-        finally:
66-            signals.request_finished.send(sender=self.__class__)
67+        response = self.process_request(req)
68 
69         try:
70             status_text = STATUS_CODE_TEXT[response.status_code]
71         except KeyError:
72             status_text = 'UNKNOWN STATUS CODE'
73         status = '%s %s' % (response.status_code, status_text)
74+
75         response_headers = [(str(k), str(v)) for k, v in response.items()]
76         for c in response.cookies.values():
77             response_headers.append(('Set-Cookie', str(c.output(header=''))))
78+
79         start_response(status, response_headers)
80+
81+        if isinstance(response, http.HttpResponseSendFile):
82+            filelike = open(response.sendfile_filename, 'rb')
83+            if 'wsgi.file_wrapper' in environ:
84+                return environ['wsgi.file_wrapper'](filelike,
85+                        response.block_size)
86+            else:
87+                # wraps close() as well
88+                from django.core.servers.basehttp import FileWrapper
89+                return FileWrapper(filelike, response.block_size)
90+
91         return response
92 
93Index: django/core/handlers/base.py
94===================================================================
95--- django/core/handlers/base.py        (revision 10054)
96+++ django/core/handlers/base.py        (working copy)
97@@ -62,6 +62,26 @@
98         # as a flag for initialization being complete.
99         self._request_middleware = request_middleware
100 
101+    def process_response(self, request_env):
102+        signals.request_started.send(sender=self.__class__)
103+        try:
104+            try:
105+                request = self.request_class(request_env)
106+            except UnicodeDecodeError:
107+                response = http.HttpResponseBadRequest()
108+            else:
109+                response = self.get_response(request)
110+
111+                # Apply response middleware
112+                if not isinstance(response, http.HttpResponseSendFile):
113+                    for middleware_method in self._response_middleware:
114+                        response = middleware_method(request, response)
115+                    response = self.apply_response_fixes(request, response)
116+        finally:
117+            signals.request_finished.send(sender=self.__class__)
118+
119+        return response
120+
121     def get_response(self, request):
122         "Returns an HttpResponse object for the given HttpRequest"
123         from django.core import exceptions, urlresolvers
124Index: django/core/handlers/modpython.py
125===================================================================
126--- django/core/handlers/modpython.py   (revision 10054)
127+++ django/core/handlers/modpython.py   (working copy)
128@@ -2,7 +2,6 @@
129 from pprint import pformat
130 
131 from django import http
132-from django.core import signals
133 from django.core.handlers.base import BaseHandler
134 from django.core.urlresolvers import set_script_prefix
135 from django.utils import datastructures
136@@ -191,21 +190,8 @@
137             self.load_middleware()
138 
139         set_script_prefix(req.get_options().get('django.root', ''))
140-        signals.request_started.send(sender=self.__class__)
141-        try:
142-            try:
143-                request = self.request_class(req)
144-            except UnicodeDecodeError:
145-                response = http.HttpResponseBadRequest()
146-            else:
147-                response = self.get_response(request)
148 
149-                # Apply response middleware
150-                for middleware_method in self._response_middleware:
151-                    response = middleware_method(request, response)
152-                response = self.apply_response_fixes(request, response)
153-        finally:
154-            signals.request_finished.send(sender=self.__class__)
155+        response = self.process_request(req)
156 
157         # Convert our custom HttpResponse object back into the mod_python req.
158         req.content_type = response['Content-Type']
159@@ -215,12 +201,16 @@
160         for c in response.cookies.values():
161             req.headers_out.add('Set-Cookie', c.output(header=''))
162         req.status = response.status_code
163-        try:
164-            for chunk in response:
165-                req.write(chunk)
166-        finally:
167-            response.close()
168 
169+        if isinstance(response, http.HttpResponseSendFile):
170+            req.sendfile(response.sendfile_filename)
171+        else:
172+            try:
173+                for chunk in response:
174+                    req.write(chunk)
175+            finally:
176+                response.close()
177+
178         return 0 # mod_python.apache.OK
179 
180 def handler(req):