Django学习之十一:真正理解Django的路由分发和反解url原理

时间:2019-01-30 18:41:04   收藏:0   阅读:429

目录

URL Dispatcher

简介

django的url dispatcher 设计是基于一个url mapper来工作的。
这个url mapper主要用在两个方向:

  1. url 匹配到 视图
  2. 通过提供的标识,反解出url

    Django provides a solution such that the URL mapper is the only repository of the URL design. You feed it with your URLconf and then it can be used in both directions:
             ** Starting with a URL requested by the user/browser, it calls the right Django view providing any arguments it might need with their values as extracted from the URL.
             ** Starting with the identification of the corresponding Django view plus the values of arguments that would be passed to it, obtain the associated URL.

模式概念

Django的URL 模式非常的清晰和优雅。一个高质量的web应用就需要一个好的URL模式。
Django的URL 助记点:

对比URLPattern 与 URLResolver (多态的体现)

通过对比两个类的定义:

技术分享图片
技术分享图片

看到,urlresolver也有resovle解析方法。只不过urlresolver的解析会再去加载子url module模块中的urlpatterns列表。然后再对列表中的进行循环匹配过程,一直嵌套下去,知道最后的return跳出返回一个ResolverMatch对象。而urlpattern的resolver直接就返回ResovlerMatch对象了。只不过前者会有重新加载获取子url module模块来获取urlpatterns的逻辑。

两个类都用同名的方法,只是表现出来的的状态有所不同。这就是面向对象多态在代码中的体现。提供相同的对外接口,展现出来的状态过程有所不同,最后返回相同的对象。

构建子路由几种方式

子路由除了减少路由前缀的冗余,还可以满足多种url前缀使用同一app的业务场景。

方式一

参照源码,从最low-level源码层面的方式,参照实例化出URLResolver对象的源码

if isinstance(view, (list, tuple)):  # 这里的view是re_path或path的第二个参数
    # For include(...) processing.
    pattern = Pattern(route, is_endpoint=False)
    urlconf_module, app_name, namespace = view
    return URLResolver(
        pattern,
        urlconf_module,
        kwargs,
        app_name=app_name,
        namespace=namespace,
    )

从源码可以看出,如果view参数是一个列表或元组类型,那么将会实例化出URLResolver对象,并且对view参数要有且有三个元素。第一个元素可以是子路由的模块的python path 也可以直接是 url对象的列表(查看URLResolver.url_patterns源码可以理解);第二个元素和第三个元素都可以空,也可以都有,但是不能只有namespace单独有。

方式二

django内置的from django.urls import include 提供生成第一种方式view参数的函数

include源码:

def include(arg, namespace=None):
    app_name = None
    if isinstance(arg, tuple):
        # Callable returning a namespace hint.
        try:
            urlconf_module, app_name = arg
        except ValueError:
            if namespace:
                raise ImproperlyConfigured(
                    ‘Cannot override the namespace for a dynamic module that ‘
                    ‘provides a namespace.‘
                )
            raise ImproperlyConfigured(
                ‘Passing a %d-tuple to include() is not supported. Pass a ‘
                ‘2-tuple containing the list of patterns and app_name, and ‘
                ‘provide the namespace argument to include() instead.‘ % len(arg)
            )
    else:
        # No namespace hint - use manually provided namespace.
        urlconf_module = arg

    if isinstance(urlconf_module, str):
        urlconf_module = import_module(urlconf_module)
    patterns = getattr(urlconf_module, ‘urlpatterns‘, urlconf_module)
    app_name = getattr(urlconf_module, ‘app_name‘, app_name)
    if namespace and not app_name:
        raise ImproperlyConfigured(
            ‘Specifying a namespace in include() without providing an app_name ‘
            ‘is not supported. Set the app_name attribute in the included ‘
            ‘module, or pass a 2-tuple containing the list of patterns and ‘
            ‘app_name instead.‘,
        )
    namespace = namespace or app_name
    # Make sure the patterns can be iterated through (without this, some
    # testcases will break).
    if isinstance(patterns, (list, tuple)):
        for url_pattern in patterns:
            pattern = getattr(url_pattern, ‘pattern‘, None)
            if isinstance(pattern, LocalePrefixPattern):
                raise ImproperlyConfigured(
                    ‘Using i18n_patterns in an included URLconf is not allowed.‘
                )
    return (urlconf_module, app_name, namespace)

可以看到提供app_name 而不提供namespace的话是会抛出异常的。

Notice:关于app_name 与 namespace 存在这样一个依赖逻辑:

  1. 提供了app_name, 可以不提供namesapce
  2. 提供了namespace,就必须提供app_name
  3. 两者都提供
  4. 两者都不提供
    意思就是有namespace必须有app_name.
    为什么要有这样的逻辑?
    因为这和反解url 算法逻辑有关。看下面说明有关算法逻辑<反解url算法逻辑>

inlucde()的参数方式,也有几种:

  1. include(‘luffyapi.urls‘) # app_name 可能来自‘luffyapi.urls.app_name‘ ,这里没提供namespace,所以‘luffyapi.urls‘中不能有app_name.‘
  2. include((‘luffyapi.urls‘, ‘luffyapi‘)) # app_name 可能被‘luffyapi.urls.app_name‘ 覆盖
  3. include((‘luffyapi.urls‘, ‘luffyapi‘), namespace=‘luffyapiuser‘)
  4. include(‘luffyapi.urls‘, namespace=‘luffyapiuser‘) # 这种方式在‘luffyapi.urls‘ 中就必须有app_name。

反解url算法逻辑

参考官方文档和from django.urls import reverse 函数的源码。大致可以这样理解:

  1. 首先,如果reverse或者 url tag(in Template file) 中,只是提供了‘name‘ url对象实例化是的name参数,那么反解逻辑很简单.直接循环一个记录字典中找到。对于name相同的,只会取出在urlpattern列表中最后一个。
  2. 如果,提供的反解名字是‘namespace:name‘ 这种模式,逻辑就变得复杂了。
    1.1 首先将namespace 作为一个app_name 查找,会yield 返回这个app_name 的所有instance的列表。
    1.2 然后django会找寻与app_name名字相同的instance namespace作为用于解析name的对象。。
    1.3 如果没有,django会使用最后部署的instance作为解析name的对象。
    1.4 如果列表中一个都没匹配上app_name,那么django会直接通过instanc namespace去查找。
    1.5 最后,如果reverse带入了current_app 参数指定当前的app ,那么就使用当前的URLResolver来解析name。最后这一点有点不好理解特别是在使用reverse与 url tag 上。
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!