有名分組 無名分組
阿新 • • 發佈:2022-04-17
無名分組
無括號
當路由層如下時:
(注意:[0-9]{4}在0-9的數字中選擇四個)
urlpatterns = [ path('admin/', admin.site.urls), re_path(r'^$', views.home), re_path(r'^wushen/[0-9]{4}/', views.wushen), re_path(r'^wushenadd/', views.wushenadd), re_path(r'', views.error) ]
檢視函式為:
def wushen(request): return HttpResponse('wushen') def wushenadd(request): return HttpResponse('wushenadd') def home(request): return HttpResponse('這是主介面') def error(request): return HttpResponse('404')
則會出現以下狀況:
因為它在匹配第一層路由時直接匹配到了最後一個,把最後一行刪了可以避免這種狀況。
有括號
re_path(r'^wushen/([0-9]{4})/', views.wushen)
會將加了括號的正則表示式匹配的內容當做位置引數傳給後面的檢視函式
此時的檢視函式為
def wushen(request, model): print(model) return HttpResponse('wushen')
有名分組
此時的路由為(\d的意思是匹配數字,+是匹配一個或者多個):
re_path(r'^wushen/(?P<year>\d+)/', views.wushen),
會將加了括號的正則表示式匹配的內容當做關鍵字引數傳遞給後面的檢視函式
關鍵字就是你尖括號裡面的名字(year)
則此時的檢視函式為:
def wushen(request, year): print(year) returnHttpResponse('wushen')
注意:當有名和無名搭配使用時會報錯
例如:此時的路由為:
re_path(r'^wushen/(?P<year>\d+)/(\d+)/', views.wushen)
檢視函式為;
def wushen(request, year, a): print(year) print(a) return HttpResponse('wushen')
只能有名有名一起用或無名無名一起用
此時的路由為:
1. re_path(r'^wushen/(?P<year>\d+)/(?P<a>\d+)/', views.wushen), 2.re_path(r'^wushen/(\d+)/(\d+)/', views.wushen),
都可以正常執行