设置重定向

时间:2019-08-21 09:32:36

标签: django redirect django-views http-status-code-404 http-status-code-301

视图中有一个mixin,其中在URL上添加了斜杠。有必要在打开不存在的页面时(例如example.com/index),立即抛出404,而不要包含301(以免在末尾添加斜线)。如果有404状态,只会引起我的注意。就像有一页一样,则不需要添加斜线。如果没有这样的页面,则在结尾处正式添加斜杠(不带重定向)。如果状态为200,那么还可以,如果状态不是,则抛出404

def is_normal_slash_count(url):
    temp_url = url
    slash_count = 0
    while temp_url.endswith('/'):
        slash_count += 1
        temp_url = temp_url[:-1]
    return (slash_count == 1, slash_count)


def replace_bad_slash(url, slash_count):
    if slash_count == 2:
        return url.replace('//', '/')
    return url.replace('/'*(slash_count-1), '')


def normalize_url(url):
    if len(url) > 1:
        if not url.endswith('/'):
            return url + '/'
        # replace the url like /contacts//// to /contacts/
        good_slash, slash_count = is_normal_slash_count(url)
        if not good_slash:
            url = replace_bad_slash(url, slash_count)
    return url

def is_bad_url(url):
    if len(url) > 1:
        good_slash, slash_count = is_normal_slash_count(url)
        if not good_slash:
            return True
    return False

class RedirectMixinView:

    def dispatch(self, *args, **kwargs):
        url = self.request.path

        redirect_setting = RedirectSettings.objects.filter(url_from=url).first()
        if redirect_setting:
            return redirect(redirect_setting.url_to, permanent=True)

        if is_bad_url(url):
            return redirect(normalize_url(url), permanent=True)
        return super(RedirectMixinView, self).dispatch(*args, **kwargs)


class LandingView(RedirectMixinView, TemplateView):
    template_name = 'base.html'

    def get(self, *args, **kwargs):
        page = Page.objects.filter(url=self.request.path).first()
        # Show 404 page
        if not page:
            raise Http404
        return super(LandingView, self).get(*args, **kwargs)

0 个答案:

没有答案