• 【Django】URL控制器


    url控制器

    from django.contrib import admin
    from django.urls import path
    
    from app01 import views
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('index/',views.index),
    ]
    

    视图

    from django.shortcuts import render
    
    # Create your views here.
    
    def index(request):
    
        import datetime
        now=datetime.datetime.now()
        ctime=now.strftime("%Y-%m-%d %X")
    
        return render(request,"index.html",{"ctime":ctime})
    

    模板

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    
    <h4>当前时间:{{ ctime }}</h4>
    
    </body>
    </html>
    

    URL控制器

    路由配置

    from django.urls import path,re_path
    
    from app01 import views
    
    urlpatterns = [
    	path('admin/', admin.site.urls),
    	# 路由配置:哪一个路径由哪一个视图函数处理
    	path('timer/', views.timer),
    	
        # 带正则表达式的【路由配置】
    	# special_case_2003(request)
    	re_path(r'^articles/2003/$', views.special_case_2003),
    	# /articles/2003/ --> views.month_archive(request)  没有分组,不会传参
    
    	# 只要分组就会将分组的数据传给year_archive:year_archive(request, 分组的数据)
    	re_path(r'^articles/([0-9]{4})/$', views.year_archive),
        # /articles/2005/ --> views.year_archive(request, '2005')
    
    	# month_archive(request, 分组的数据1, 分组的数据2)
    	re_path(r'^articles/([0-9]{4})/([0-9]{2})/$', views.month_archive),
        # /articles/2005/03/ --> views.month_archive(request, '2005', '03')
    ]
    

    有名分组

    使用命名的正则表达式组来捕获URL 中的值并以关键字 参数传递给视图 r'(?P<...>)'

    from django.urls import path,re_path
    
    from app01 import views
    
    urlpatterns = [
    	path('admin/', admin.site.urls),
        
        # /articles/2005/ --> views.year_archive(request, year='2005')
    	re_path(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive),
    
    	# /articles/2005/03/ --> views.month_archive(request, year='2005', month='03')
    	re_path(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.month_archive),
        
    ]
    

    分发

    URLconf中的path可以直接将路径请求发送给对应的视图函数进行处理,也可以转发给另一个URLconf,使用include函数设置要转发的URLconf,子URLconf接收到的是匹配过后的余下字符串。降低耦合度

    project/urls.py/

    from django.urls import path,re_path
    
    from app01 import views
    
    urlpatterns = [
    	path('admin/', admin.site.urls),
    	# 将路径请求发送给对应的视图函数
    	path('timer/', views.timer),
    	
        # 转发给另一个URLconf,
    	re_path(r'^app01/', include('app01.urls')),
    	re_path(r'^app02/', include('app02.urls')),
    ]
    

    app01 /urls.py/

    from django.urls import path,re_path
    
    from app01 import views
    
    urlpatterns = [
    	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),
    ]
    

    app02 /urls.py/

    from django.urls import path,re_path
    
    from app01 import views
    
    urlpatterns = [
    	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),
    ]
    

    访问路路径就变成了:

    .../app01/articles/2018/.../app01/articles/2018/11

    .../app02/articles/2018/.../app02/articles/2018/11

    反向解析

    在需要URL 的地方,对于不同层级,Django 提供不同的工具用于URL 反查:

    1. 在模板中:使用url 模板标签。

    2. 在Python 代码中:使用from django.urls import reverse()函数

    app01/urls.py: re_path(r'xx', views.xx, name='xxx')

    from django.conf.urls import url
    
    from . import views
    
    urlpatterns = [
        #...
        re_path(r'^articles/([0-9]{4})/$', views.year_archive, name='news-year-archive'),
        #...
    ]
    

    在模板中: {% url 'xxx' xxxx %}

    <a href="{% url 'news-year-archive' 2012 %}">2012 Archive</a>
    
    <ul>
        {% for yearvar in year_list %}
        <li><a href="{% url 'news-year-archive' yearvar %}">{{ yearvar }} Archive</a></li>
        {% endfor %}
    </ul>
    

    在views中: reverse('xxx', args=(xxxx,)

    from django.urls import reverse
    from django.http import HttpResponseRedirect
    
    def redirect_to_year(request):
        # ...
        year = 2006
        # ...
        return HttpResponseRedirect(reverse('news-year-archive', args=(year,))) # 同redirect("/path/")
    

    名称空间

    命名空间(英语:Namespace)是表示标识符的可见范围。一个标识符可在多个命名空间中定义,它在不同命名空间中的含义是互不相干的。这样,在一个新的命名空间中可定义任何标识符,它们不会与任何已有的标识符发生冲突,因为已有的定义都处于其它命名空间中。 由于name没有作用域,Django在反解URL时,会在项目全局顺序搜索,当查找到第一个name指定URL时,立即返回 我们在开发项目时,会经常使用name属性反解出URL,当不小心在不同的app的urls中定义相同的name时,可能会导致URL反解错误,为了避免这种事情发生,引入了命名空间。

    project的urls.py:

    urlpatterns = [
        re_path(r'^admin/', admin.site.urls),
        re_path(r'^app01/', include("app01.urls",namespace="app01")),
        re_path(r'^app02/', include("app02.urls",namespace="app02")),
    ]
    

    app01.urls:

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

    app02.urls:

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

    app01.views

    from django.core.urlresolvers import reverse
    
    def index(request):
    	return HttpResponse(reverse("app01:index"))
    

    app02.views

    from django.core.urlresolvers import reverse
    
    def index(request):
    	return HttpResponse(reverse("app02:index"))
    

    django2.0版的path

    URLconf的示例:

    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字符串中,可以使用<>获取符合条件的字符串,转换成对应数据类型传递给views处理函数中的变量名,例如int:year匹配int类型的变量,传递给views处理函数中的year变量。如果没有提供数据类型的话,则直接把对应字符串传递下去(不包括/)。

    路径匹配类型包含以下几种:

    • str:匹配去除/后的非空字符串,这是默认的匹配方式。

    • int:匹配非零整数,返回int类型数据。

    • slug:匹配由ASCII字母或数字、以及-和_组成的字符串。

    • uuid:匹配格式化的UUID,即必须包含-,字母小写。

    • path:匹配包含/的非空字符串。

    注册自定义转化器:
    对于一些复杂或者复用的需要,可以定义自己的转化器。转化器是一个类或接口,它的要求有三点:

    1. regex 类属性,字符串类型
    2. to_python(self, value) 方法,value是由类属性 regex 所匹配到的字符串,返回具体的Python变量值,以供Django传递到对应的视图函数中。
    3. to_url(self, value) 方法,和 to_python 相反,value是一个具体的Python变量值,返回其字符串,通常用于url反向引用。
    class FourDigitYearConverter:  
        regex = '[0-9]{4}'  
        def to_python(self, value):  
            return int(value)  
        def to_url(self, value):  
            return '%04d' % value
    

    使用register_converter 将其注册到URL配置中:

    from django.urls import register_converter, path  
    from . import converters, views  
    
    register_converter(converters.FourDigitYearConverter, 'yyyy')  
    
    urlpatterns = [  
        path('articles/2003/', views.special_case_2003),  
        path('articles/<yyyy:year>/', views.year_archive),  
        ...  
    ]
    
  • 相关阅读:
    Windows各个文件夹介绍
    Zabbix使用外部命令fping处理ICMP ping的请求
    QT 样式表实例
    QT 样式表基础知识
    cocos2d-js入门一
    try throw catch typeid
    cocos2d-x入门三 分层设计框架
    cocos2d-x入门二 helloworld实例运行与创建
    cocos2d-x入门一
    批量操作QT UI中的控件
  • 原文地址:https://www.cnblogs.com/q1ang/p/9980281.html
Copyright © 2020-2023  润新知