设置重定向
重定向的状态码分为301和302,前者时永久性跳转,后者是临时性跳转的,两者的区别在于搜索引擎的网页抓取。301重定向是永久的重定向,搜索引擎在抓取新内容的同时会将旧的网址替换为重定向之后的网址。302跳转时暂时的跳转,搜索引擎会抓取新内容而保留旧的网址。因为服务器返回302代码,所以搜索引擎认为新的网址只是暂时的。
主要讲述redirect函数,函数时将HttpResponseRedirect和HttpResponsePermanentRedirect的功能进行完善和组合。 重定向类HttpResponseRedirect和HttpResponsePermanentRedirect分别代表HTTP状态码302和301。从redirect的定义过程可以看出,该函数运行原理如下:
- 判断参数permanent的真假性来选择重定向的函数,若为True,则调用HttpResponsePermanentRedirect(301)来完成重定向过程,若为False,则调用HttpResponseRedirect(302)。
- 由于HttpResponsePermanentRedirect和HttpResponseRedirect只支持路由地址的传入,因此函数redirect调用resolve_url方法对参数to进行判断。若参数to是路由地址,则直接将参数to的参数值返回;若参数to是路由命名,则使用reverse函数转换路由地址;若参数to是模型对象,则将模型转换成相应的路由地址(这种方法的使用频率相对较低)。
示例如下:
# index的urls.py
from django.urls import path
from . import views
urlpatterns = [
# 定义首页的路由
path('', views.index, name='index'),
# 定义商城的路由
path('shop', views.shop, name='shop')
]
# index的views.py
from django.http import HttpResponseRedirect
from django.http import HttpResponsePermanentRedirect
from django.shortcuts import reverse
from django.shortcuts import render, redirect
def index(request):
return redirect('index:shop' ,permanent=True)
# 设置302的重定向
# url = reverse('index:shop')
# return HttpResponseRedirect(url)
# 设置301的重定向
# return HttpResponsePermanentRedirect(url)
def shop(request):
return render(request, 'index.html')