• 08.URL调度器示例


    1.URL调度器示例

    1.1 创建django项目结构

    创建父级结构

    django-admin startproject url_project
    
    • 1

    进入父级目录

    cd url_project
    python manage.py startapp url_app
    
    • 1
    • 2

    1.2 路径转换器

    str:匹配任何非空字符串,不包括路径分隔符’/'。如果转换器不包含在表达式中,这是默认值。
    int:匹配零或任何正整数。返回一个int。
    slug:匹配由ASCII字母或数字组成的字符串,以及横线和下划线字符。例如, building-your-1st-django_site可以匹配,django_@site是不可以匹配的。
    uuid:匹配格式化的UUID。为防止多个URL映射到同一页面,必须包含破折号,并且字母必须是小写。例如,075194d3-6885-417e-a8a8-6c931e272f00。返回一个 UUID实例。
    path:匹配任何非空字符串,包括路径分隔符 ‘/’,可以匹配完整的URL路径,而不仅仅是URL路径的一部分str,使用时要谨慎,因为可能造成后续的所有url匹配都失效。

    1.3Django-URL调度器测试

    在父级url

    from django.contrib import admin
    from django.urls import path, include
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('url_app/', include('url_app.urls'))
    ]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    在子级url

    from django.contrib import admin
    from django.urls import path
    from . import views
    urlpatterns = [
        path('articles/2003/',views.articles_2003),
        path('articles//',views.articles_year),
        path('articles//', views.articles_year_month),
        path('articles///', views.articles_year_month_slug),
        path('articles//',views.articles_str),
        path('articles//',views.articles_path),
        path('articles//',views.articles_uuid)
    ]
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    在子级view

    from django.shortcuts import render, HttpResponse
    
    # Create your views here.
    
    def articles_2003(request):
        return HttpResponse('articles_2003')
    
    def articles_year(request, year):
        return HttpResponse(f'articles_year.year{year}')
    
    def articles_year_month(request, year, month):
        return HttpResponse(f'articles_year.year{year},{month}')
    
    def articles_year_month_slug(request, year, month, slug):
        return HttpResponse(f'articles_year.year{year},{month},{slug}')
    
    def articles_str(request,username):
        return HttpResponse(f'articles_str,username:{username}')
    
    def articles_path(request,path):
        return HttpResponse(f'articles_str,path:{path}')
    
    def articles_uuid(request,uuid):
        return HttpResponse(f'articles_str,uuid:{uuid}')
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    1.4 URL调度器总结

    从URL中捕获值,请使用尖括号

    捕获的值可以选择包含转换器类型。例如,用于 int:name捕获,前面的int指整数参数,name是参数的名称

    没有必要添加一个前导斜杠,因为每个URL都有,例如,使用articles而不是/articles。

    示例请求说明:

    /articles/2005/03/ 匹配列表中的第三个条目。Django会调用这个函数,views.month_archive(request, year=2005, month=3)
    /articles/2003/ 会匹配列表中的第一个模式,而不是第二个模式,因为模式是按顺序测试的,而第一个模式是第一个要传递的测试。看看利用匹配顺序插入像这样的特殊情况。在这里,Django会调用这个函数 views.special_case_2003(request)
    /articles/2003 不匹配任何这些模式,因为每种模式都要求URL以斜线结尾,不过在浏览器访问时,会自动添加 / 。
    **/articles/2003/03/building-a-django-site/ **将匹配最终模式。Django会调用这个函数 。views.article_detail(request, year=2003, month=3, slug=“building-a-django-site”)

    2. 自定义路径转换器

    2.1 方法概述

    转换器是需要包含以下内容的类:

    • 应该regex类属性,作为应该re匹配字符串
    • to_python(self,value)方法,它处理的匹配字符串转换要传递到视图函数的类型
    • to_url(self, value)方法, 用于处理将python类型转换为URL中使用的字符串

    2.2 测试

    创建converters.py文件编写规则

    class MyYearConverter(object):
        regex = '[0-9]{4}'
    
        def to_python(self, value):
            return int(value)
        
        def to_url(self, value):
            return '%04d' % value
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    注册并使用规则

    from django.contrib import admin
    from django.urls import path
    from . import views
    
    # 注册自定义路径转换器
    from . import converters
    from django.urls import register_converter
    register_converter(converters.MyYearConverter, 'yyyy')
    urlpatterns = [
        path('atricles//',views.articles_year)
    ]
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    3.URL调度器中正则表达式的使用

    3.1方法概述

    ​ 使用正则表达式匹配路径,请使用 re_path()而不是path()
    ​ 在Python正则表达式中,命名正则表达式组的语法是(?Ppattern),其中name是组的名称,并且 pattern是一些要匹配的模式

    3.2测试

    url地址

    from django.contrib import admin
    from django.urls import path,re_path
    from . import views
    urlpatterns = [
        re_path(r'^articles/(?P[0-9]{4})/$', views.articles_year), # 4位数字
        re_path('^articles/(?P\d+/$)', views.articles_year), #任意个数字
        re_path(r'^articles/(?P[0-9]{4})/(?P[0-9]{2})/$', views.articles_year_month) # 年份4位,月份2为
        re_path(r'^comments/(?:page-(?P\d+)/)?$', views.comments) # page-加一个数字,嵌套正则
    ]
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    view视图

    from django.shortcuts import render, HttpResponse
    
    # Create your views here.
    
    def articles_2003(request):
        return HttpResponse('articles_2003')
    
    def articles_year(request, year):
        return HttpResponse(f'articles_year.year{year}')
    
    def articles_year_month(request, year, month):
        return HttpResponse(f'articles_year.year{year},{month}')
    
    def comments(request, page_number):
        return HttpResponse(f'comments:{page_number}')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    4.默认值使用

    4.1方法概述

    当我们在查询数据时,就可以使用一个默认值,当用户未在指定url地址(页数)就默认为第1页

    4.2测试

    url地址

    from django.contrib import admin
    from django.urls import path,re_path
    from . import views
    urlpatterns = [
        # 使用默认值
        path('blog/',views.do_page),
        path('blog//',views.do_page)
    ]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    view视图

    from django.shortcuts import render, HttpResponse
    def do_page(request, num=1):
        return HttpResponse(f'page={num}')
    
    
    • 1
    • 2
    • 3
    • 4

    5.url异常处理

    5.1概述

    handler400- 状态码400
    handler403- 状态码403
    handler404- 状态码404
    handler500- 状态码500
    当我们的状态码为某个值时,做出相应的反馈

    5.2 测试

    当我们找不到路由时,返回一个视图

    1. 在 settings中修改配置:
    DEBUG = False
    ALLOWED_HOSTS = ['*', ]
    
    • 1
    • 2
    1. 在主应用的urls中配置:
    import url_app
    # 异常处理
    handler404 = "url_app.views.page_not_found"
    
    • 1
    • 2
    • 3
    1. 在polls应用(子应用)的views中添加函数page_not_found:
    from django.shortcuts import render, HttpResponse
    #handler404 处理函数
    def page_not_found(request, exception):
        return HttpResponse('404出现异常')
    
    • 1
    • 2
    • 3
    • 4
    1. 浏览器测试访问,找不到匹配的路由
      在这里插入图片描述

    6.引用其它URL调度器

    • 多个 patterns
    from django.contrib import admin
    from django.urls import path,re_path,include
    from . import views
    morenzhi_patterns = [
        path('blog/',views.do_page),
        path('blog//',views.do_page)
    ]
    urlpatterns = [
        # 1.使用其他include包含其他patterns
        path('', include(morenzhi_patterns))
    ]
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 使用include消除重复前缀
    from django.contrib import admin
    from django.urls import path,re_path,include
    from . import views
    urlpatterns = [
        # 2.使用include消除重复前缀
        path('articles/',include([
                path('articles/2003/',views.articles_2003),
                path('articles//',views.articles_year),
        ]))
    ]
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 传递捕获的参数
      在主urls中配置:
    from django.contrib import admin
    from django.urls import path, include
    import poll_app
    import url_app
    urlpatterns = [
        path('/',include("poll_app.urls"))
    ]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    对应的 polls 应用下的urls中配置:

    from django.urls import path
    from . import views
    
    urlpatterns = [
        path('arg_test/', views.arg_usernameapp_test)
    ]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    对应的 polls 应用下的views中编写函数:

    from django.shortcuts import render, HttpResponse
    
    # Create your views here.
    
    def arg_usernameapp_test(request,usernameapp):
        return HttpResponse(f':{usernameapp}')
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    7.额外的参数

    url地址

    from django.urls import path
    from . import views
    
    urlpatterns = [
        path('arg_test/', views.arg_usernameapp_test),
        path('param_test/', views.param_test, {'user':'root','password':'1234'})
    ]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    views视图

    from django.shortcuts import render, HttpResponse
    
    def param_test(request, usernameapp, user, password):
        return HttpResponse(f'user:{user}, password:{password}')
    
    
    • 1
    • 2
    • 3
    • 4
    • 5

    8.URL反向解析(重定向)

    8.1 概述

    url调度器除了从用户发起请求,到匹配对应的view,还能在python程序中调用进行匹配,通过 path或re_path 中 的name属性进行解析
    在模板中,使用url模板标签
    在Python代码中(主要是views),使用 reverse() 函数
    在模型实例中,使用 get_absolute_url() 方法

    8.2 在视图中重定向url

    views视图中

    from django.shortcuts import render, HttpResponse,HttpResponseRedirect
    from django.urls import reverse
    
    # Create your views here.
    def first_request(request):
        # return HttpResponse('first_request')
        return HttpResponseRedirect(reverse('news-year-archive',args=(22,)))
    
    def year_archive(request, year):
        return HttpResponse(f'重定向成功year:{year}')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    url中:

    from django.urls import path
    from . import views
    urlpatterns = [
        path('first_request_url/', views.first_request),
        path('articles//', views.year_archive, name='news-year-archive'),
    ]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    8.3在模板中测试

    在views.py中

    from django.urls import path
    from . import views
    urlpatterns = [
        path('first_request_url/', views.first_request),
        path('articles//', views.year_archive, name='news-year-archive'),
        path('do_html/', views.do_html)
    ]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    在url路由中

    from django.shortcuts import render, HttpResponse,HttpResponseRedirect
    from django.urls import reverse
    
    # Create your views here.
    def first_request(request):
        # return HttpResponse('first_request')
        return HttpResponseRedirect(reverse('news-year-archive',args=(22,)))
    
    def year_archive(request, year):
        return HttpResponse(f'重定向成功year:{year}')
    
    def do_html(request):
        return render(request, 'redirect_test.html')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    templates模板中

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <a href="{% url 'news-year-archive' 2004 %}">url反向解析</a>
    </body>
    </html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    9.命名控件——解决重定向名称错乱

    9.1概述

    主要用于配合url反向解析 使用,多个不同的urls文件中可能配置同名的 name,那么为了进行区分,给不同的urls进行不同的命名,切记同一个项目下命名空间不能重复!

    9.2 测试

    urls.py中

    from django.urls import path
    from . import views
    app_name = 'reverse'
    urlpatterns = [
        path('first_request_url/', views.first_request),
        path('articles//', views.year_archive, name='news-year-archive'),
        path('do_html/', views.do_html)
    ]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    views.py

    from django.shortcuts import render, HttpResponse,HttpResponseRedirect
    from django.urls import reverse
    
    # Create your views here.
    def first_request(request):
        # return HttpResponse('first_request')
        return HttpResponseRedirect(reverse('reverse:news-year-archive',args=(22,)))
    
    def year_archive(request, year):
        return HttpResponse(f'重定向成功year:{year}')
    
    def do_html(request):
        return render(request, 'redirect_test.html')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    template

    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Documenttitle>
    head>
    <body>
        <a href="{% url 'reverse:news-year-archive' 2004 %}">url反向解析a>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
  • 相关阅读:
    【项目实战】日志系统
    STM32教程 使用硬件SPI和模拟SPI驱动W25Q64芯片
    linux安装Yum
    某银行核心业务双活存储架构升级建设实践分享
    SQL语句常见分类
    Django4.0 + Web + MySQL5.7 实现简单登录操作
    java python php网上拍卖网站系统nodejs+vue+elementui
    Java基于微信小程序的校园生活互助小助手
    分库分表番外:多数据源/动态数据源实现
    C语言const修饰指针场景demo
  • 原文地址:https://blog.csdn.net/m0_63953077/article/details/127889481