zoukankan      html  css  js  c++  java
  • 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()),
    ]
  • 相关阅读:
    npm WARN saveError ENOENT: no such file or directory的解决方法
    简单的webpack打包案例
    JS中用encodeURIComponent编码,后台JAVA解码
    说 Redis
    let the cat out of the bag
    简述C# volatile 关键字
    螃蟹怎么分公母?是用冷水上锅还是热水蒸呢?
    Mysql截取字符串 更新字段的部分内容
    Ajax 获取数据attr后获取不到
    如何限制域名访问?白名单机制
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13309019.html
Copyright © 2011-2022 走看看