确定重定向在重定向之前是否会在视图中生成 404 状态代码



我有一个系统,其中大部分功能都依赖于用户设置的会话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)

resolve函数仅检查 url 是否是 url 规则中定义的有效 url。例如,如果Propertyurl 如下所示

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,这意味着此时不会抛出任何Resolver404

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

最新更新