Best way to handle obsolete urls in django

I am working on a large news publishing platform. Basically rebuild everything from scratch with django. Now that we're almost ready to run, I need to handle the redirected URLs. What is the best way to do this, bearing in mind that I have to deal with tens of thousands of obsolete URLs?

The logic should work as follows: if none of the existing URLs / matches that match match, start the URL of the completely obsolete Redirect URL patterns / views to see if it can redirect to the new URL before error return 404.

How to do it?

+4
source share
3 answers

, :

from django.http import Http404
from legacy.urls import urlpatterns

class LegacyURLsMiddleware(object):

    def process_response(self, request, response):
        if response.status_code != 404:
            return response
        for resolver in urlpatterns:
            try:
                match = resolver.resolve(request.path[1:])
                if match:
                    return match.func(request, *match.args, **match.kwargs)
            except Http404:
                pass
        return response

MIDDLEWARE_CLASSES. urls.py , URL- , . URL- URL-. , -.

+1

, , URL-, . .

  • . urlpatterns!

    urls.py:

    urlpatterns = patterns(
        '',
        # all your patterns
        url(r'^.+/', 'app.views.fallback')
    )
    

    views.py:

    from django.http.response import HttpResponseRedirect, Http404
    
    def fallback(request):
        if is_legacy(request.path):
            return HttpResponseRedirect(convert(request.path))
        raise Http404
    
  • http 404.

    urls.py:

    handler404 = 'app.views.fallback'
    

    views.py

    from django.http.response import HttpResponseRedirect
    from django.views.defaults import page_not_found
    
    def fallback(request):
        if is_legacy(request.path):
            return HttpResponseRedirect(convert(request.path))
        return page_not_found(request)
    

    , , DEBUG False 404.

0

Use the Jacobian django-multiurl . There is a django ticket to solve the problem someday, but at the moment it django-multiurlworks very well.

Before:

# urls.py
urlpatterns = patterns('',
    url('/app/(\w+)/$', app.views.people),
    url('/app/(\w+)/$', app.views.place),  # <-- Never matches
)

After:

# urls.py
from multiurl import multiurl, ContinueResolving
from django.http import Http404

urlpatterns = patterns('', multiurl(
    url('/app/(\w+)/$', app.views.people), # <-- Tried 1st
    url('/app/(\w+)/$', app.views.place),  # <-- Tried 2nd (only if 1st raised Http404)
    catch=(Http404, ContinueResolving)
))
0
source

Source: https://habr.com/ru/post/1539399/


All Articles