Code

Ticket #3228: smartslash-3.1.diff

File smartslash-3.1.diff, 10.2 KB (added by Andy Gayton <andy-django@…>, 7 years ago)

fixed typo in docs/middleware.txt

Line 
1Index: django/middleware/common.py
2===================================================================
3--- django/middleware/common.py (revision 6837)
4+++ django/middleware/common.py (working copy)
5@@ -5,6 +5,7 @@
6 from django import http
7 from django.core.mail import mail_managers
8 from django.utils.http import urlquote
9+from django.core import urlresolvers
10 
11 class CommonMiddleware(object):
12     """
13@@ -16,6 +17,12 @@
14           this middleware appends missing slashes and/or prepends missing
15           "www."s.
16 
17+            - If APPEND_SLASH is set and the initial URL doesn't end with a
18+              slash, and it is not found in urlpatterns, a new URL is formed by
19+              appending a slash at the end. If this new URL is found in
20+              urlpatterns, then an HTTP-redirect is returned to this new URL;
21+              otherwise the initial URL is processed as usual.
22+
23         - ETags: If the USE_ETAGS setting is set, ETags will be calculated from
24           the entire page content and Not Modified responses will be returned
25           appropriately.
26@@ -33,27 +40,48 @@
27                 if user_agent_regex.search(request.META['HTTP_USER_AGENT']):
28                     return http.HttpResponseForbidden('<h1>Forbidden</h1>')
29 
30-        # Check for a redirect based on settings.APPEND_SLASH and settings.PREPEND_WWW
31+        # Check for a redirect based on settings.APPEND_SLASH
32+        # and settings.PREPEND_WWW
33         host = request.get_host()
34         old_url = [host, request.path]
35         new_url = old_url[:]
36-        if settings.PREPEND_WWW and old_url[0] and not old_url[0].startswith('www.'):
37+
38+        if (settings.PREPEND_WWW and old_url[0] and
39+                not old_url[0].startswith('www.')):
40             new_url[0] = 'www.' + old_url[0]
41-        # Append a slash if append_slash is set and the URL doesn't have a
42-        # trailing slash or a file extension.
43-        if settings.APPEND_SLASH and (not old_url[1].endswith('/')) and ('.' not in old_url[1].split('/')[-1]):
44-            new_url[1] = new_url[1] + '/'
45-            if settings.DEBUG and request.method == 'POST':
46-                raise RuntimeError, "You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to %s%s (note the trailing slash), or set APPEND_SLASH=False in your Django settings." % (new_url[0], new_url[1])
47+
48+        # Append a slash if APPEND_SLASH is set and the URL doesn't have a
49+        # trailing slash and there is no pattern for the current path
50+        if settings.APPEND_SLASH and (not old_url[1].endswith('/')):
51+            try:
52+                urlresolvers.resolve(request.path)
53+            except urlresolvers.Resolver404:
54+                new_url[1] = new_url[1] + '/'
55+                if settings.DEBUG and request.method == 'POST':
56+                    raise RuntimeError, (""
57+                    "You called this URL via POST, but the URL doesn't end "
58+                    "in a slash and you have APPEND_SLASH set. Django can't "
59+                    "redirect to the slash URL while maintaining POST data. "
60+                    "Change your form to point to %s%s (note the trailing "
61+                    "slash), or set APPEND_SLASH=False in your Django "
62+                    "settings.") % (new_url[0], new_url[1])
63+
64         if new_url != old_url:
65-            # Redirect
66-            if new_url[0]:
67-                newurl = "%s://%s%s" % (request.is_secure() and 'https' or 'http', new_url[0], urlquote(new_url[1]))
68+            # Redirect if the target url exists
69+            try:
70+                urlresolvers.resolve(new_url[1])
71+            except urlresolvers.Resolver404:
72+                pass
73             else:
74-                newurl = urlquote(new_url[1])
75-            if request.GET:
76-                newurl += '?' + request.GET.urlencode()
77-            return http.HttpResponsePermanentRedirect(newurl)
78+                if new_url[0]:
79+                    newurl = "%s://%s%s" % (
80+                        request.is_secure() and 'https' or 'http',
81+                        new_url[0], urlquote(new_url[1]))
82+                else:
83+                    newurl = urlquote(new_url[1])
84+                if request.GET:
85+                    newurl += '?' + request.GET.urlencode()
86+                return http.HttpResponsePermanentRedirect(newurl)
87 
88         return None
89 
90Index: tests/regressiontests/middleware/__init__.py
91===================================================================
92Index: tests/regressiontests/middleware/tests.py
93===================================================================
94--- tests/regressiontests/middleware/tests.py   (revision 0)
95+++ tests/regressiontests/middleware/tests.py   (revision 0)
96@@ -0,0 +1,93 @@
97+# -*- coding: utf-8 -*-
98+
99+import unittest
100+
101+from django.test import TestCase
102+from django.http import HttpRequest
103+from django.middleware.common import CommonMiddleware
104+from django.conf import settings
105+
106+class CommonMiddlewareTest(TestCase):
107+    def _get_request(self, path):
108+        request = HttpRequest()
109+        request.META = {
110+            'SERVER_NAME': 'testserver',
111+            'SERVER_PORT': 80,
112+        }
113+        request.path = "/middleware/%s" % path
114+        return request
115+
116+    def test_append_slash_have_slash(self):
117+        """
118+        tests that urls with slashes go unmolested
119+        """
120+        settings.APPEND_SLASH = True
121+        request = self._get_request('slash/')
122+        self.assertEquals(CommonMiddleware().process_request(request), None)
123+
124+    def test_append_slash_slashless_resource(self):
125+        """
126+        tests that matches to explicit slashless urls go unmolested
127+        """
128+        settings.APPEND_SLASH = True
129+        request = self._get_request('noslash')
130+        self.assertEquals(CommonMiddleware().process_request(request), None)
131+
132+    def test_append_slash_slashless_unknown(self):
133+        """
134+        tests that APPEND_SLASH doesn't redirect to unknown resources
135+        """
136+        settings.APPEND_SLASH = True
137+        request = self._get_request('unknown')
138+        self.assertEquals(CommonMiddleware().process_request(request), None)
139+
140+    def test_append_slash_redirect(self):
141+        """
142+        tests that APPEND_SLASH redirects slashless urls to a valid pattern
143+        """
144+        settings.APPEND_SLASH = True
145+        request = self._get_request('slash')
146+        r = CommonMiddleware().process_request(request)
147+        self.assertEquals(r.status_code, 301)
148+        self.assertEquals(r['Location'], 'http://testserver/middleware/slash/')
149+
150+    def test_append_slash_no_redirect_on_POST_in_DEBUG(self):
151+        """
152+        tests that while in debug mode, an exception is raised with a warning
153+        when a failed attempt is made to POST to an url which would normally be
154+        redirected to a slashed version
155+        """
156+        settings.APPEND_SLASH = True
157+        settings.DEBUG = True
158+        request = self._get_request('slash')
159+        request.method = 'POST'
160+        self.assertRaises(
161+            RuntimeError,
162+            CommonMiddleware().process_request,
163+            request)
164+        try:
165+            CommonMiddleware().process_request(request)
166+        except RuntimeError, e:
167+            self.assertTrue('end in a slash' in str(e))
168+
169+    def test_append_slash_disabled(self):
170+        """
171+        tests disabling append slash functionality
172+        """
173+        settings.APPEND_SLASH = False
174+        request = self._get_request('slash')
175+        self.assertEquals(CommonMiddleware().process_request(request), None)
176+
177+    def test_append_slash_quoted(self):
178+        """
179+        tests that urls which require quoting are redirected to their slash
180+        version ok
181+        """
182+        settings.APPEND_SLASH = True
183+        request = self._get_request('needsquoting#')
184+        r = CommonMiddleware().process_request(request)
185+        self.assertEquals(r.status_code, 301)
186+        self.assertEquals(
187+            r['Location'],
188+            'http://testserver/middleware/needsquoting%23/')
189+
190Index: tests/regressiontests/middleware/models.py
191===================================================================
192Index: tests/regressiontests/middleware/urls.py
193===================================================================
194--- tests/regressiontests/middleware/urls.py    (revision 0)
195+++ tests/regressiontests/middleware/urls.py    (revision 0)
196@@ -0,0 +1,7 @@
197+from django.conf.urls.defaults import patterns
198+
199+urlpatterns = patterns('',
200+    (r'^noslash$', 'view'),
201+    (r'^slash/$', 'view'),
202+    (r'^needsquoting#/$', 'view'),
203+)
204Index: tests/urls.py
205===================================================================
206--- tests/urls.py       (revision 6837)
207+++ tests/urls.py       (working copy)
208@@ -14,4 +14,7 @@
209     
210     # django built-in views
211     (r'^views/', include('regressiontests.views.urls')),
212+
213+    # test urlconf for middleware tests
214+    (r'^middleware/', include('regressiontests.middleware.urls')),
215 )
216Index: docs/middleware.txt
217===================================================================
218--- docs/middleware.txt (revision 6837)
219+++ docs/middleware.txt (working copy)
220@@ -58,12 +58,18 @@
221   which should be a list of strings.
222 
223 * Performs URL rewriting based on the ``APPEND_SLASH`` and ``PREPEND_WWW``
224-  settings. If ``APPEND_SLASH`` is ``True``, URLs that lack a trailing
225-  slash will be redirected to the same URL with a trailing slash, unless the
226-  last component in the path contains a period. So ``foo.com/bar`` is
227-  redirected to ``foo.com/bar/``, but ``foo.com/bar/file.txt`` is passed
228-  through unchanged.
229+  settings.
230 
231+  **New in Django development version:** If ``APPEND_SLASH`` is ``True`` and
232+  the initial URL doesn't end with a slash, and it is not found in urlpatterns,
233+  a new URL is formed by appending a slash at the end. If this new URL is found
234+  in urlpatterns, then an HTTP-redirect is returned to this new URL; otherwise
235+  the initial URL is processed as usual.
236+
237+  So ``foo.com/bar`` will be redirected to ``foo.com/bar/`` if you do not
238+  have a valid urlpattern for ``foo.com/bar``, and do have a valid urlpattern
239+  for ``foo.com/bar/``.
240
241   If ``PREPEND_WWW`` is ``True``, URLs that lack a leading "www." will be
242   redirected to the same URL with a leading "www."
243