Login

AppendSlashMiddleware

Author:
sjzabel
Posted:
March 6, 2007
Language:
Python
Version:
Pre .96
Tags:
middleware
Score:
2 (after 2 ratings)

I won't be able to debug this until tonight... so if you see this message there may still be bugs in this

This Middleware replaces the behavior of the APPEND_SLASH in the CommonMiddleware. Please set APPEND_SLASH = False if you are going to use this Middleware.

Add the key defined by APPENDSLASH to the view_kwargs and a True or False to determine the behaivor of the appended slashes. For instance I set my DEFAULTBEHAVIOR to the default of True, then to override that behaivor I add 'AppendSlash':False to the URLs that I wish to have no slash.

Example

urlpatterns = patterns('some_site.some_app.views', (r'^test/no_append$','test_no_append',{'AppendSlash':False}), (r'^test/append/$','test_append'), )

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
__license__ = "Python"
__copyright__ = "Copyright (C) 2007, Stephen Zabel"
__author__ = "Stephen Zabel - sjzabel@gmail.com"


from django.conf import settings
from django.http import HttpResponseRedirect, get_host

APPENDSLASH = 'AppendSlash'
DEFAULTBEHAVIOR = settings.APPENDSLASH_DEFAULTBEHAVIOR and settings.APPENDSLASH_DEFAULTBEHAVIOR or True

class AppendSlashRedirect:
    def process_view(self, request, view_func, view_args, view_kwargs):
        if SSL in view_kwargs:
            append = view_kwargs[APPENDSLASH]
            del view_kwargs[APPENDSLASH]
        else:
            append = DEFAULTBEHAVIOR

        if not append == request.path[-1] != '/':
            return self._redirect(request, append)

    def _redirect(self, request, append):
        if settings.DEBUG and request.method == 'POST':
            raise RuntimeError, \
"""You can't perform a redirect while maintaining POST data.
Please structure your views so that redirects only occur during GETs."""

        d = {}
        d['protocol'] = request.is_secure() and 'https' or 'http'
        d['host'] = request.get_host(request)
        d['path'] = append and request.path()+"/" or request.path()[:-1]
        d['parms'] = request.GET and '?' + request.GET.urlencode() or ''

        newurl = "%(protocol)s://%(host)s%(path)s%(parms)s" % d

        return HttpResponsePermanentRedirect(newurl)

More like this

  1. Smart append slash middleware by akaihola 7 years, 6 months ago
  2. SSL Middleware by sjzabel 8 years, 5 months ago
  3. TLS(SSL) middleware, per URL pattern or whole site by robmadole 4 years, 9 months ago
  4. RegEx redirect fallback middleware by bowdengm 3 years, 1 month ago
  5. Add get_addr() method to request object by nikmolnar 2 years, 8 months ago

Comments

JimH10 (on December 21, 2008):

What is SSL?

What is the purpose of

"settings.APPENDSLASH_DEFAULTBEHAVIOR and settings.APPENDSLASH_DEFAULTBEHAVIOR"

?

#

Please login first before commenting.