Django2.0转化器(converters)

1.Djang2.0默认支持以下5个path转化器:

1.str,匹配除了路径分隔符(/)之外的非空字符串,这是默认的形式
2.int,匹配正整数,包含0。
3.slug,匹配字母、数字以及横杠、下划线组成的字符串。
4.uuid,匹配格式化的uuid,如 075194d3-6885-417e-a8a8-6c931e272f00。
5.path,匹配任何非空字符串,包含了路径分隔符。
一个简单的例子:
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('articles/<int:year>/<int:month>/<slug>/', views.article_detail),  
]
匹配结果

请求URL

匹配项

视图函数调用形式

/articles/2005/03/

第3个

views.month_archive(request,year=2005,month=3)

/articles/2003/

第1个

views.special_case_2003(request)

/articles/2003

-

-

/articles/2003/03/building-a-django-site

第4个

views.articles-detail(request, year=2003,month=3,slug=”building-a-django-site”)

2. 注册自定义转化器

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

   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),  
    ...  
]
原文地址:https://www.cnblogs.com/haoqirui/p/9986620.html