Login

django redirects middleware a bit more fleixble

Author:
robertrv
Posted:
October 23, 2009
Language:
Python
Version:
1.1
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. Template tag - list punctuation for a list of items by shapiromatron 3 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months, 1 week ago
  5. Help text hyperlinks by sa2812 12 months ago

Comments

Please login first before commenting.