【问题标题】:Determine if redirect will produce a 404 status code in view prior to redirecting在重定向之前确定重定向是否会在视图中产生 404 状态代码
【发布时间】:2020-04-24 01:16:18
【问题描述】:

我有一个系统,其中大部分功能取决于用户设置的会话 cookie。自然地,我允许轻松更改此会话(属性),以便用户可以在浏览整个应用程序时无缝地查看新信息。

例如,用户正在查看系统中的单位,当他们选择一个新属性时,将显示新选择的属性的单位。很简单。但是,有一种情况是用户正在查看一个单元并且他们更改了一个属性。显然,他们正在查看的单元不再找到,所以页面 404 的。

我想知道重定向将 404,以便我可以将它们重定向到主页。我该怎么做?

我能想到的所有检查方式(即解析或 HttpRespsonse)都不会显示错误。

from urllib.parse import urlparse

import requests
from django.contrib import messages
from django.http import HttpResponse
from django.shortcuts import redirect, get_object_or_404
from django.urls import reverse, resolve, Resolver404

from apps.properties.models import Property

def set_property_session(request, property_id):

    redirect_url = request.META.get('HTTP_REFERER')
    # to check if it resolves, we must gather the path from the url
    path_to_check = urlparse(redirect_url).path
    try:
        # check to ensure the path resolves
        resolve(path_to_check)
        response = HttpResponse(path_to_check)
        # 200, not 404, when it should be while I am testing
        print(response.status_code)
        print(f'{path_to_check} is a valid path for redirection, we are going to go there in a sec...')
    except Resolver404:
        # error so go back home
        redirect_url = reverse('home', args=[client_url])
        print(f'{path_to_check} is not a valid path')
        return redirect(redirect_url)

    # 0 means the user wants to clear their session
    if property_id == 0:
        request.session['property'] = None
        Logger.info('property session set to none')
    else:
        # set the session to whichever property the user wants
        request.session['property'] = get_object_or_404(Property, pk=property_id)

    return redirect(redirect_url)


【问题讨论】:

    标签: python django python-3.x django-views http-status-code-404


    【解决方案1】:

    resolve 函数仅检查 url 是否为您的 url 规则中定义的有效 url。例如,如果Property url 看起来像这样

    url(r'^property/(?P<id>[-\w.]+)', Property.as_view(), name='property')
    

    path('property/<str:id>', Property.as_view(), name='property')
    

    并且您只有一个 id 为 1 的 Property 实例,以下两个 url 都将解析,因为它们是根据规则的有效 url:

    财产/1

    属性/4

    因此,在您的代码中,resolve(path_to_check) 将始终正确解析,因为 HTTP_REFERER 将始终是有效的 url(如果未更改)。 response = HttpResponse(path_to_check) 只是创建了一个 200 see here,这意味着此时不会抛出 Resolver404

    我认为你可以“解决”这个问题的唯一方法是在你的视图中处理它并返回一个重定向,或者在这个函数中,在你获得你的属性后,检查你的属性和单元 ID 是否匹配并处理相应地。 我很确定您可以使用相关对象来处理此问题,如here

    【讨论】:

      猜你喜欢
      • 2012-07-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-29
      • 1970-01-01
      • 2015-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多