AppendSlashMiddleware

 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 6 years, 2 months ago
  2. SSL Middleware by sjzabel 7 years, 1 month ago
  3. TLS(SSL) middleware, per URL pattern or whole site by robmadole 3 years, 4 months ago
  4. Add get_addr() method to request object by nikmolnar 1 year, 4 months ago
  5. RegEx redirect fallback middleware by bowdengm 1 year, 9 months ago

Comments

JimH10 (on December 21, 2008):

What is SSL?

What is the purpose of

"settings.APPENDSLASH_DEFAULTBEHAVIOR and settings.APPENDSLASH_DEFAULTBEHAVIOR"

?

#

(Forgotten your password?)