Login

django redirects middleware a bit more fleixble

Author:
robertrv
Posted:
October 23, 2009
Language:
Python
Version:
1.1
Tags:
generic redirects contrib
Score:
0 (after 0 ratings)

This is replace for django.contrib.redirects.RedirectFallbackMiddleware which redirects exact matches as well as startswith matches for the redirect.old_path

I had a problem with my urls, because are dynamically generic, so I can't create one redirect entry on the database for each possible url. So I made django redirects to search any redirect with the exact match or any database entry being the head of my url, for example:

I have django redirects which redirects /calendars/3434/ --> / . But when I have a 404 on /calendars/3434/c/2009/10/23/ now it redirects properly. So my redirects now acts as /calendars/3434/*

 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
from django.contrib.redirects.models import Redirect
from django import http
from django.conf import settings

class RedirectFallbackMiddleware(object):
    def process_response(self, request, response):
        if response.status_code != 404:
            return response # No need to check for a redirect for non-404 responses.
        path = request.get_full_path()
        try:
            paths = [path]
            current_path = request.path
            while current_path and current_path != '/' and '/' in current_path:
                paths.append(current_path)
                current_path = current_path.rsplit('/',2)[0]+'/'
            
            r = Redirect.objects.get(site__id__exact=settings.SITE_ID, old_path__in=paths)
        except Redirect.DoesNotExist:
            r = None
        if r is None and settings.APPEND_SLASH:
            # Try removing the trailing slash.
            try:
                r = Redirect.objects.get(site__id__exact=settings.SITE_ID,
                    old_path=path[:path.rfind('/')]+path[path.rfind('/')+1:])
            except Redirect.DoesNotExist:
                pass
        if r is not None:
            if r.new_path == '':
                return http.HttpResponseGone()
            return http.HttpResponsePermanentRedirect(r.new_path)

        # No redirect was found. Return the response.
        return response

More like this

  1. Simple Django event calendar template tag by sandinmyjoints_ 4 years, 1 month ago
  2. Database cleanup by skyjur 5 years ago
  3. All Imports Checker by madhav.bnk 5 years, 8 months ago
  4. Improved Pickled Object Field by taavi223 5 years, 11 months ago
  5. SSL Redirect Middleware by zbyte64 7 years ago

Comments

Please login first before commenting.