django3.0路由学习
作者:互联网
一、路径的匹配
from django.contrib import admin from django.urls import path from index 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:slug>/', views.article_detail), ]url.py
from django.http import HttpResponse def special_case_2003(request): return HttpResponse("This is the special 2003") def year_archive(request,year): return HttpResponse("This is year archive,Year number is %d" % year) def month_archive(request,year,month): return HttpResponse("This is month archive,It's %d year %d month" %(year,month)) def article_detail(request,year,month,slug): return HttpResponse("This is month articl details,It's %d year, %d month,slug is %s" %(year,month,slug))view.py
1.由/分开,获取参数用尖括号,可以指定类型
2.路径后面一定要有/不然匹配不到任何路径
3.传递给视图函数view包含的参数有request实例以及路径中获取到的参数
4.顺序匹配
二、转换器
尖括号内的东西有以下几类
- str,匹配除/的非空字符串,未指定转换器默认
- int,匹配整形
- slug, 匹配任意由 ASCII 字母或数字以及连字符和下划线组成的短标签
- uuid,这个不知道干啥的
- path,匹配包含/的非空字段
path('articles/<path:anythings>/',views.anythings)
def anythings(request,anythings): return HttpResponse("match nonthing above,your input is %s" % anythings)
访问http://127.0.0.1:8000/articles/mylove/hello/check/
响应match nonthing above,your input is mylove/hello/check
三、自定义转换器
class FourDigitYearConverter: regex = '[0-9]{4}' def to_python(self, value): return int(value) def to_url(self, value): return '%04d' % valueconverter
from django.urls import path,register_converter
register_converter(converter.FourDigitYearConverter,'yyyy')
查看register_converter文件可以看到django规定的集中默认的转换器的规则,regex是匹配到的正则表达值。
to_python 是前段往后端python程序传的类型或值,可以在这里做特殊转换
四、正则表达式转换器
path---> re_path
转换器写法: (?P<匹配后参数名>正则表达式)
例如:re_path('articles/?P<year>[0-9]{4}/$',views.function)
五、include
将同类的url指定到app里的urlconf。
标签:articles,return,views,month,学习,year,path,django3.0,路由 来源: https://www.cnblogs.com/felix-snail/p/12387360.html