Django2.X-設置重定向

設置重定向

重定向的狀態碼分爲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')
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章