Login

AppendSlashMiddleware

Author:
sjzabel
Posted:
March 6, 2007
Language:
Python
Version:
Pre .96
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 - [email protected]"


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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 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.