Django的路由层 路由控制之有名分组

有名分组

上面的示例使用简单的、没有命名的正则表达式组(通过圆括号)来捕获URL 中的值并以位置 参数传递给视图。

在更高级的用法中,可以使用命名的正则表达式组来捕获URL 中的值并以关键字 参数传递给视图。

有名分组类似于 关键字传参

在Python 正则表达式中,命名正则表达式组的语法是(?P<name>pattern),其中name 是组的名称,pattern 是要匹配的模式。 (name组的名称是视图函数,接受的参数,pattern是正则匹配方式)

下面是以上URLconf 使用命名组的重写

ursl.py

from django.contrib import admin
from django.urls import path, re_path

from app01 import views

urlpatterns = [
    path('admin/', admin.site.urls),

    # 路由配置 ---> 视图函数
    # re_path(r'^articles/2003/$', views.special_case_2003),  # special_case_2003(request)
    # re_path(r'^articles/([0-9]{4})/$', views.year_archive),  # year_archive(request, 2009)
    # re_path(r'^articles/([0-9]{4})/([0-9]{2})/$', views.month_archive),  # month_archive(request, 2009, 12)

    # month_archive(request, year=2009, month=12)
    re_path(r'^articles/(?P<year>[0-9]{4})/(?P<mouth>[0-9]{2})/$', views.month_archive),
    # re_path(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$', views.article_detail),

]

views.py

位置参数调换也可以 其实是关键字参数

传递参数 一定是 组的名字 year mouth

from django.shortcuts import render, HttpResponse

# Create your views here.


def special_case_2003(request):
    
    return HttpResponse("special_case_2003")


def year_archive(request, year):

    return HttpResponse(year)


def month_archive(request, mouth, year):

    return HttpResponse(year+"-"+mouth)

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')。

    '''

在实际应用中,这意味你的URLconf 会更加明晰且不容易产生参数顺序问题的错误 —— 你可以在你的视图函数定义中重新安排参数的顺序。当然,这些好处是以简洁为代价;

原文地址:https://www.cnblogs.com/mingerlcm/p/14168891.html