学习笔记,仅供参考
url匹配优先级
首先我们看下面这两段代码,考虑输入地址http://127.0.0.1:8000/birthday/1997/9/28,服务器会返回给我们什么页面:
urls.py
from django.contrib import admin
from django.urls import path
from . import views
from django.urls import re_path
#.表示从当前包里导入
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'year/(\d{4})/', views.year),
re_path(r'birthday/(\d{4})/', views.page_birth_year),
re_path(r'birthday/(\d{4})/(\d{1,2})/(\d{1,2})/', views.page_birth),
]
views.py
def year(request, y):
print(type(y))
html = "输入年份为:" + y
return HttpResponse(html)
def page_birth(request, year, month, day):
html = "生日为:"+year+"年"+month+"月"+day+"日"
return HttpResponse(html)
def page_birth_year(request, year):
html = "出身年份为:"+year+"年"
return HttpResponse(html)
由于我们的匹配规则是从头(索引为0
)到尾(索引为len(urlpatterns)-1
)进行搜索匹配的,所以当我们的url地址匹配到birthday/(\d{4})/
时,就已经匹配上了,所以就不会再进行匹配了,也就不会匹配到birthday/(\d{4})/(\d{1,2})/(\d{1,2})/
浏览器响应页面: