Django的路由转换器的使用

路由转换器

# 项目结构
mycodes  # 仓库
      |-- my_project
	     |-- myproject
	     |      |-- urls.py # 总路由
	     |-- apps
	     |	      |-- users
	     |	      |	      |-- urls.py  # 子路由
	     |-- utils 		# 工具包,路由转换器就放在这里
	     |	      |-- converters.py 		# 路由转换器
	     |-- manage.py

一般会把路由转换器放在一个叫做命名为utils的工具包里.

首先编写路由转换器仓库/项目目录/项目主目录/utils/converters.py 中路由转换器的内容:

class UsernameConverter:
    """自定义路由转换器"""
    # 定义正则表达式
    regex = '[a-zA-Z0-9_-]{5,20}'

    def to_python(self, value):
        # 将匹配结果传递到视图内部时使用
        # 返回str还是int主要看需求,纯数字的可以返回int
        return str(value)

    def to_url(self, value):
        # 将匹配结果用于反向解析传值时使用
        return str(value)


class MobileConverter:
    regex = '1[3-9]\d{9}'

    def to_python(self, value):
        return int(value)

    def to_url(self, value):
        return str(value)

然后在主路由中注册路由转换器

主路由的位置在仓库/MyProject/myproject/urls.py

# 注册路由转换器
from django.urls import register_converter
from meiduo_mall.utils.converters import UsernameConverter
from meiduo_mall.utils.converters import MobileConverter

register_converter(UsernameConverter,'username')
register_converter(MobileConverter,'mobile')

在子路由中使用路由转换器

子路由的位置在仓库/MyProject/myproject/apps/子应用/urls.py

urlpatterns = [
    # 检查重复用户接口 20200702
    path(r'usernames/<username:username>/count/',views.UsernameCountView.as_view()),
    # 检查重复的手机号借口
    path(r'mobiles/<mobile:mobile>/count/',views.MobileCountView.as_view()),
]
posted @ 2020-07-07 18:54  Linuxbugs  阅读(557)  评论(0编辑  收藏  举报