首页 > 其他 > 详细

django3.0路由学习

时间:2020-03-01 00:23:29      阅读:84      评论:0      收藏: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 % value
converter

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。

django3.0路由学习

原文:https://www.cnblogs.com/felix-snail/p/12387360.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!