路由转发器

规则

from django.urls import register_converter # 导入register_converter用来注册规则
class Year(object):

    regex = "\d{4}" # 正则规则,regex 变量是固定的

    def to_python(self,value): # to_python 固定函数,value 是用来接收正则匹配成功的value
        return value

class Month(object):

    regex = "\d{2}" # 正则规则,regex 变量是固定的

    def to_python(self,value): # to_python 固定函数,value 是用来接收正则匹配成功的value


        return value

register_converter(Year,"year") # 注册规则 第一个参数是累,第二个是使用该规则的别名
register_converter(Month,"month") # 注册规则

使用方法

urlpatterns = [
    path("articles/<year:year2>/<month:month2>/", article_archive), # 在urls绑定视图函数的时候使用,<规则别名:关键字传参给试图函数,第二个参数要和视图函数一致> ,
]
posted @ 2022-11-25 17:52  zhq9  阅读(13)  评论(0编辑  收藏  举报