Django3 Django 路由分發,反向解析,2.0版本的path


urls配置像Django 所支撐網站的目錄。它的本質是URL與要為該URL調用的視圖函數之間的映射表;你就是以這種方式告訴Django,對於客戶端發來的某個URL調用哪一段邏輯代碼對應執行。

1.簡單的urls配置

from django.urls import path,re_path from app01 import views urlpatterns = [ re_path(r'^articles/2003/$', views.special_case_2003), re_path(r'^articles/([0-9]{4})/$', views.year_archive), re_path(r'^articles/([0-9]{4})/([0-9]{2})/$', views.month_archive), re_path(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$', views.article_detail), ]

注意:

  • 若要從URL 中捕獲一個值,只需要在它周圍放置一對圓括號。
  • 不需要添加一個前導的反斜杠,因為每個URL 都有。例如,應該是^articles 而不是 ^/articles
  • 每個正則表達式前面的'r' 是可選的但是建議加上。它告訴Python 這個字符串是“原始的” —— 字符串中任何字符都不應該轉義

示例:

 

''' 一些請求的例子: /articles/2005/03/ 請求將匹配列表中的第三個模式。Django 將調用函數views.month_archive(request, '2005', '03')。 /articles/2005/3/ 不匹配任何URL 模式,因為列表中的第三個模式要求月份應該是兩個數字。 /articles/2003/ 將匹配列表中的第一個模式不是第二個,因為模式按順序匹配,第一個會首先測試是否匹配。請像這樣自由插入一些特殊的情況來探測匹配的次序。 /articles/2003 不匹配任何一個模式,因為每個模式要求URL 以一個反斜線結尾。 /articles/2003/03/03/ 將匹配最后一個模式。Django 將調用函數views.article_detail(request, '2003', '03', '03')。 '''

 

2.有名分組

  上面的示例使用簡單的、沒有命名的正則表達式組(通過圓括號)來捕獲URL 中的值並以位置 參數傳遞給視圖。在更高級的用法中,可以使用命名的正則表達式組來捕獲URL 中的值並以關鍵字 參數傳遞給視圖

在Python 正則表達式中,命名正則表達式組的語法是(?P<name>pattern),其中name 是組的名稱,pattern 是要匹配的模式。

下面是以上URLconf 使用命名組的重寫:

from django.urls import path,re_path from app01 import views urlpatterns = [ re_path(r'^articles/2003/$', views.special_case_2003), re_path(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive), re_path(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.month_archive), re_path(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<day>[0-9]{2})/$', views.article_detail), ]

這個實現與前面的示例完全相同,只有一個細微的差別:捕獲的值作為關鍵字參數而不是位置參數傳遞給視圖函數。例如:

    ''' /articles/2005/03/ 請求將調用views.month_archive(request, year='2005', month='03')函數,而不是views.month_archive(request, '2005', '03')。 /articles/2003/03/03/ 請求將調用函數views.article_detail(request, year='2003', month='03', day='03')。 '''

 

分發功能:

適用場景:按照我們上面的urls的寫法,如果我們有10個應用,每個應用有200條路由,那么我們就要在urls里寫上2000條.其實我們應該把相對應的路由寫到對應的應用中(在應用中新建一個urls.py,其他名稱也可以),這就用到了分發功能

項目下的urls配置:

from django.contrib import admin from django.urls import path,re_path,include from app01 import views urlpatterns = [ path('admin/', admin.site.urls), path('timer/', views.timer), # 分發功能:下面的意思:只要是在瀏覽器中以app01開頭的請求,都轉到app01.urls路由里去分發
    re_path(r"^app01/",include("app01.urls")) ]

 

應用中urls配置:

from django.contrib import admin from django.urls import path,re_path from app01 import views urlpatterns = [ # path('admin/', admin.site.urls), # path('timer/', views.timer), # 路由配置: 路徑------>視圖函數,哪個路徑由哪一個視圖函數處理
 re_path(r"^articles/2003/$",views.special_2003),#如果路徑匹配成功了,相當於調用views.special_2003(request)
    re_path(r"^articles/([0-9]{4})/$",views.year), re_path(r"^articles/([0-9]{4})/([0-9]{2})/$",views.month),

# 有名分組:可以使用命名的正則表達式組來捕獲URL 中的值並以關鍵字 參數傳遞給視圖。
    re_path(r"^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$",views.month), # 傳遞參數時就會按照關鍵字參數來傳遞:views.month(request,year=2009,month=02),同樣的,在view視圖函數中,month函數也應該接收2個關鍵字參數
]

 

反向解析

  在使用Django 項目時,一個常見的需求是獲得URL 的最終形式,以用於嵌入到生成的內容中(視圖中和顯示給用戶的URL等)或者用於處理服務器端的導航(重定向等)。人們強烈希望不要硬編碼這些URL(費力、不可擴展且容易產生錯誤)或者設計一種與URLconf 毫不相關的專門的URL 生成機制,因為這樣容易導致一定程度上產生過期的URL。

在需要URL 的地方,對於不同層級,Django 提供不同的工具用於URL 反查:

  • 在模板中:使用url 模板標簽。
  • 在Python 代碼中:使用from django.urls import reverse()函數

urls.py

from django.contrib import admin from django.urls import path,re_path,include from app01 import views urlpatterns = [ path('admin/', admin.site.urls), path('timer/', views.timer), #反向解析流程:當用戶在瀏覽器上請求login地址時,轉到views.login中,在render()的時候,要解析login.html頁面,當在頁面中發現 #模版語法{% url "LOG"}的時候,會到urls中找別名為LOG的那一條記錄,然后取出相應的地址,渲染到login.html中,替換模板語法.

    # 此時,login/可以更改為任何你想要更改的內容
    path('login/', views.login,name="LOG"),

]

 

模版文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登錄驗證</title>
</head>
<body>
<form action="{% url 'LOG' %}" method="post"> 用戶名 <input type="text" name="user"> 密碼 <input type="password" name="pwd">
    <input type="submit">
</form>
</body>
</html>

 

視圖函數中:

from django.shortcuts import render,HttpResponse from django.urls import reverse # Create your views here.
def timer(request): import time ctime = time.strftime("%Y-%m-%d %X",time.localtime()) return render(request,"timer.html",{"date":ctime}) def special_2003(request): return HttpResponse("2003") def year(request,y): return HttpResponse(y) def month(request,year,month): return  HttpResponse(year+"-"+month) def login(request): # 校驗用戶名密碼,得從post請求中,獲取到用戶輸入的user和pwd,所有的請求信息都在request中
    #1.獲取請求方式是GET還是POST
    print(reverse("LOG")) print(request.method) if request.method=="GET": # render的時候,會渲染login.html,當遇到模板語法{}的時候,會到urls中找相應的別名,然后取出路徑,渲染到login.html中.再返回給瀏覽器
        return render(request, "login.html") else: # 2.post請求信息在request.POST中,這是一個字典形式的數據
        print(request.POST) user = request.POST.get("user") pwd = request.POST.get("pwd") if user =="nick" and pwd=="123": return  HttpResponse("登錄成功!") else: return  HttpResponse("登錄失敗,請檢查用戶名密碼!")

 注意:如果urls路徑中有正則表達式,則需要把相應的規則轉換成一個參數傳遞,否則會報錯:Reverse for 'yd' with no arguments not found. 1 pattern(s) tried: ['app01/articles/([0-9]{4})/$']

路徑帶正則的view函數:

# *_*coding:utf-8 *_*
from django.shortcuts import render,HttpResponse from django.urls import reverse # Create your views here.
def timer(request): import time ctime = time.strftime("%Y-%m-%d %X",time.localtime()) return render(request,"timer.html",{"date":ctime}) def special_2003(request): return HttpResponse("2003") def year(request,y): #這里必須傳遞一個參數 
    url = reverse("yd",args=(2000,)) print(url) return HttpResponse(url) def month(request,year,month): return  HttpResponse(year+"-"+month)

 

帶正則匹配的urls:

from django.contrib import admin from django.urls import path,re_path from app01 import views urlpatterns = [ # path('admin/', admin.site.urls),
    # path('timer/', views.timer),

# 路由配置: 路徑------>視圖函數,哪個路徑由哪一個視圖函數處理
 re_path(r"^articles/2003/$",views.special_2003,name="sc2003"),#如果路徑匹配成功了,相當於調用views.special_2003(request)
    re_path(r"^articles/([0-9]{4})/$",views.year,name="yd"), re_path(r"^articles/([0-9]{4})/([0-9]{2})/$",views.month), ]

 

名稱空間:

      命名空間(英語:Namespace)是表示標識符的可見范圍。一個標識符可在多個命名空間中定義,它在不同命名空間中的含義是互不相干的。這樣,在一個新的命名空間中可定義任何標識符,它們不會與任何已有的標識符發生沖突,因為已有的定義都處於其它命名空間中。

由於name沒有作用域,Django在反解URL時,會在項目全局順序搜索,當查找到第一個name指定URL時,立即返回
我們在開發項目時,會經常使用name屬性反解出URL,當不小心在不同的app的urls中定義相同的name時,可能會導致URL反解錯誤,為了避免這種事情發生,引入了命名空間.
project中urls:
urlpatterns = [
    re_path(r'^admin/', admin.site.urls),
#include的時候,傳遞一個元組參數,第一個是匹配的路由,第二個是名稱空間(可以隨意命名)
    re_path(r'^app01/', include(("app01.urls",app01"))),
    re_path(r'^app02/', include(("app02.urls","app02"))),
]

app01中的urls:

urlpatterns = [
    re_path(r'^index/', index,name="index"),
]

app02中的urls:

urlpatterns = [
    re_path(r'^index/', index,name="index"),
]

app01.views.py:

from django.core.urlresolvers import reverse

def index(request):

    return  HttpResponse(reverse("app01:index"))

app02.views.py:

from django.core.urlresolvers import reverse

def index(request):
#
    return  HttpResponse(reverse("app02:index"))

 Django2.0 path

urlpatterns = [  
    re_path('articles/(?P<year>[0-9]{4})/', year_archive),  
    re_path('article/(?P<article_id>[a-zA-Z0-9]+)/detail/', detail_view),  
    re_path('articles/(?P<article_id>[a-zA-Z0-9]+)/edit/', edit_view),  
    re_path('articles/(?P<article_id>[a-zA-Z0-9]+)/delete/', delete_view),  
]

  考慮下這樣的兩個問題:

  第一個問題,函數 year_archive 中year參數是字符串類型的,因此需要先轉化為整數類型的變量值,當然year=int(year) 不會有諸如如TypeError或者ValueError的異常。那么有沒有一種方法,在url中,使得這一轉化步驟可以由Django自動完成?

  第二個問題,三個路由中article_id都是同樣的正則表達式,但是你需要寫三遍,當之后article_id規則改變后,需要同時修改三處代碼,那么有沒有一種方法,只需修改一處即可?

  在Django2.0中,可以使用 path 解決以上的兩個問題。

示例:

from django.urls import path  
from . import views  
urlpatterns = [  
    path('articles/2003/', views.special_case_2003),  
    path('articles/<int:year>/', views.year_archive),  
    path('articles/<int:year>/<int:month>/', views.month_archive),  
    path('articles/<int:year>/<int:month>/<slug>/', views.article_detail),  
]

 

基本規則:

  • 使用尖括號(<>)從url中捕獲值。
  • 捕獲值中可以包含一個轉化器類型(converter type),比如使用 <int:name> 捕獲一個整數變量。若果沒有轉化器,將匹配任何字符串,當然也包括了 / 字符。
  • 無需添加前導斜杠。

 

path轉換器:

  Django默認支持以下5個轉化器:

  • str,匹配除了路徑分隔符(/)之外的非空字符串,這是默認的形式
  • int,匹配正整數,包含0。
  • slug,匹配字母、數字以及橫杠、下划線組成的字符串。
  • uuid,匹配格式化的uuid,如 075194d3-6885-417e-a8a8-6c931e272f00。
  • path,匹配任何非空字符串,包含了路徑分隔符

自定義轉換器:新建一個py文件

# -*- coding: utf-8 -*-

class MonPath(object):

    #定義規則:定義一個2位數
    regex ="[0-9]{2}"

    def to_python(self,value):
        return int(value)

    def to_url(self,value):#用於反向解析
        return "%04d" % value

pro urls.py:

from django.contrib import admin
from django.urls import path,re_path,include
from app01 import views
from django.urls import  register_converter
from app01.urlconvert import  *   #urlconvert是我們新建的py文件

register_converter(MonPath,"mm") #mm是起的別名.可以隨便取
urlpatterns = [
    path('admin/', admin.site.urls),
    path('timer/', views.timer),



#使用自定義轉換器之前,需要早django.urls中導入register_converter,導入我們自定義的轉換器,然后使用register_converter,來注冊自定義轉換器


    path("articles/<mm:month>",views.path_month)



]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM