Django URL routing matching process

Guixian 2021-01-22 13:41:59
django url routing matching process

1 Django How to handle a request

When a user requests Django A page of the site , Here is Django The system decides which Python The algorithm the code uses :

  1. Django Determine the use of root URLconf modular . Usually , This is a ROOT_URLCONF Set the value of the ( namely settings Medium ROOT_URLCONF), But if it comes in HttpRequest The object owns urlconf attribute ( Through middleware settings ), Its value will be used instead of ROOT_URLCONF Set up . Can be in django/core/handlers/ Find the logic .

    class BaseHandler:
    def _get_response(self, request):
    if hasattr(request, 'urlconf'):
    urlconf = request.urlconf
    resolver = get_resolver(urlconf)
    resolver = get_resolver()
  2. Django Load the Python Modules and look for available urlpatterns . It is django.urls.path() and ( or ) django.urls.re_path() The sequence of instances (sequence). It's actually what we wrote
  3. Django We're going to traverse each one in order URL Pattern , And then in the requested URL Stop after matching to the first pattern , And with path_info matching . This is the key to route matching , The relevant logic is in django/urls/ There are several important concepts , Such as RegexPatternRoutePatternURLPatternURLResolver. among URLResolver There's nested logic , Detailed below .
  4. Once you have URL The match is successful ,Django Import and call related views , This view is a Python function ( Or class based views class-based view ). If the match is successful, a ResolverMatch object .
  5. without URL Matched , Or there is an exception in the matching process ,Django An appropriate error handling view is called .

This article details 2、3, namely urlpatterns Related concepts and route matching process .

2 URL The configuration file

stay Django 2 After that, we usually use path/re_path To set the route , There is also a special method include .

  • path: For normal paths
  • re_path: For regular paths
  • include: I'll give you one url Profile import

The following example :

urlpatterns = [
path('index/', views.index), # Normal path
re_path(r'^articles/([0-9]{4})/$', views.articles), # Regular path
path("app01/", include("app01.urls")),

Profile above , Set up 3 strip urlpattern, They are the common paths index/ And The view function views.index, Regular path ^articles/([0-9]{4})/$ And view functions views.articles binding .app01/ and app01.urls binding ,app01.urls Not a view function , It's a sub module urlpatterns.
You can see urlpattern You can put a url Bind to view function , Or with a son urlpattern Binding .

2.1 path、re_path

Several functions for setting the route are defined in django/urls/ in .

def include(arg, namespace=None):
return (urlconf_module, app_name, namespace)
def _path(route, view, kwargs=None, name=None, Pattern=None):
if isinstance(view, (list, tuple)):
# For include(...) processing.
pattern = Pattern(route, is_endpoint=False)
urlconf_module, app_name, namespace = view
return URLResolver(
elif callable(view):
pattern = Pattern(route, name=name, is_endpoint=True)
return URLPattern(pattern, view, kwargs, name)
raise TypeError('view must be a callable or a list/tuple in the case of include().')
path = partial(_path, Pattern=RoutePattern)
re_path = partial(_path, Pattern=RegexPattern)

First of all, let's look at path and re_path, These two functions are called functools Below partial It encapsulates .partial Simply put, the function is to fix some parameters of a function , Returns a new function . Detailed documentation is available partial file .
It's not hard to understand path and re_path, They just bind different Pattern Parametric _path function . Further inspection _path Internal logic ,

  • The first branch If the binding is a list perhaps tuple, Use URLResolver Parse , In fact, this is the time to use include To define urlpattern.
  • In another case, if it's bound view Is callable , Use it URLPattern Parse .URLPattern Medium pattern Parameters are based on the adoption of path/re_path The methods correspond to RoutePattern/RegexPattern.

2.2 include

def include(arg, namespace=None):
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)
return (urlconf_module, app_name, namespace)

include The way to do it is through import_module To be defined url Module import . Return to an argument urlconf modular 、app_name、 Namespace namespace A tuple of components . Back to the one just above _path The first branch of . Substitute the parameters in this tuple into URLResolver And back to .

3 URLPattern And URLResolver

3.1 URLPattern

As mentioned above, if url In the definition, the binding is one that can be called directly view. That's using URLPattern Go straight to the analysis .

class URLPattern:
def __init__(self, pattern, callback, default_args=None, name=None):
# Need to match urlpattern, This is based on path still re_path Namely RoutePattern or RegexPattern Example
self.pattern = pattern
self.callback = callback # the view
self.default_args = default_args or {} = name
def resolve(self, path):
call RoutePattern or RegexPattern In the example of match Method to match ( Note that this is not re In the module match)
match = self.pattern.match(path)
if match:
new_path, args, kwargs = match
# Pass any extra_kwargs as **kwargs.
# Match successfully returns `ResolverMatch`
return ResolverMatch(self.callback, args, kwargs,, route=str(self.pattern))

URLPattern During initialization, one of the pattern It's based on the use of path/re_path They correspond to each other RoutePattern or RegexPattern. In fact, it is to specify whether the matching pattern is normal route or regular route .

3.2 URLResolver

URLResolver The core of the source code is resolve function , Is to introduce a path, Match .

class URLResolver:
def resolve(self, path):
path = str(path) # path may be a reverse_lazy object
tried = []
# matching path
match = self.pattern.match(path)
if match:
new_path, args, kwargs = match
# If the match is successful , Then continue to match its url_patterns
for pattern in self.url_patterns:
# This pattern May be URLPattern, It could be URLResolver; If it is URLPattern, If the match is successful, return ResolverMatch; If it is URLResolver, Will be called recursively .
sub_match = pattern.resolve(new_path)
if sub_match:
# Match successfully returns ResolverMatch
return ResolverMatch(
[self.app_name] + sub_match.app_names,
[self.namespace] + sub_match.namespaces,
self._join_route(current_route, sub_match.route),
raise Resolver404({'tried': tried, 'path': new_path})
raise Resolver404({'path': path})

URLResolver The key logic is Loop match pattern The process , If pattern yes URLPattern If the match is successful, return to ResolverMatch, If it's another one URLResolver, The recursive call is implemented .

Django Through this URLResolver Multi level URL To configure .

4 summary

Django There are several core concepts of routing matching path/re_path/include、RegexPattern/RoutePattern、URLPattern/URLResolver.
First use partial encapsulation _path, Bind a pattern Matching mode (RegexPattern/RoutePattern), This is used many times later pattern. And then it's based on view Tuple or callable view function , Separate use URLResolver and URLPattern Parse , Both classes will be returned to ResolverMatch, It calls back the result after successful matching (view and args etc. ).
In this paper, from the overall point of view, it is generally explained that Django Routing matching process , Some of the key points will be explained in detail .


  1. 前后端分离有什么了不起,手把手教你用Python爬下来!
  2. 在 Azure 上执行一些简单的 python 工作
  3. 推荐 :利用Python的混合集成机器学习(附链接)
  4. Cunning or orthodox Kung Fu? The most complete usage of Python derivation
  5. It's estimated that 80% of pandas people have to hang up!
  6. What's so great about the separation of front and rear ends? Hand in hand teach you to climb down with Python!
  7. Doing some simple Python work on azure
  8. Recommendation: hybrid integrated machine learning using python (link attached)
  9. Learning PPO algorithm programming from scratch (Python version)
  10. Python OpenCV 图片模糊操作 blur 与 medianBlur
  11. Python OpenCV image blur operation blur and mediablur
  12. 成功解决cv2.error: OpenCV(4.1.2) C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:182: err
  13. Cv2.error solved successfully: opencv (4.1.2) C:: (projects / opencv Python / opencv modules / imgproc / SRC)\ color.cpp:182 : err
  14. Python 中使用 virtualenv 管理虚拟环境
  15. Using virtualenv to manage virtual environment in Python
  16. 如何使用Python执行系统命令?Python学习教程!
  17. How to use Python to execute system commands? Python tutorial!
  18. 快速掌握Python中的循环技术
  19. Quickly grasp the loop technology in Python
  20. Python主流Web框架之Tornado
  21. appium+python自动化63-使用Uiautomator2报错问题解决
  22. Tornado: the mainstream Python Web Framework
  23. Appium + Python automation 63 - using uiautomator2 to solve the problem of error reporting
  24. 爬虫+django,打造个性化API接口
  25. Crawler + Django to create personalized API interface
  26. 爬虫+django,打造个性化API接口
  27. Crawler + Django to create personalized API interface
  28. C、C++、Java、PHP、Python主要应用在哪里方面?
  29. C. Where are the main applications of C + +, Java, PHP and python?
  30. Python 无限级分类树状结构生成算法 「实用代码」
  31. Python infinite classification tree structure generation algorithm "practical code"
  32. 【Azure 存储服务】Python模块(azure.cosmosdb.table)直接对表存储(Storage Account Table)做操作示例
  33. [azure storage service] Python module( azure.cosmosdb.table )Direct operation example of storage account table
  34. 【Azure 存储服务】Python模块(azure.cosmosdb.table)直接对表存储(Storage Account Table)做操作示例
  35. [azure storage service] Python module( azure.cosmosdb.table )Direct operation example of storage account table
  36. openpose c++ 配置教程 + python api
  37. Openpose C + + configuration tutorial + Python API
  38. PYTHON爬虫实战_垃圾佬闲鱼爬虫转转爬虫数据整合自用二手急速响应捡垃圾平台_3(附源码持续更新)
  39. 使用python javaSerializationTools模块拼接生成 8u20 Gadget
  40. 萌新入门之python基础语法
  41. python中hmac模块的使用
  42. Python crawler_ Garbage man idle fish crawler turn crawler data integration self use second hand rapid response garbage collection platform_ 3 (with continuous source update)
  43. Using Python javaserialization tools module to generate 8u20 gadget
  44. The basic syntax of Python
  45. The use of HMAC module in Python
  46. 攻防世界web进阶区Web_python_block_chain详解
  47. Attack and defense world web advanced zone Web_ python_ block_ Details of chain
  48. pandas DataFrame的新增行列,修改、删除、筛选、判断元素以及转置操作
  49. Add rows and columns, modify, delete, filter, judge elements and transpose operations in pandas dataframe
  50. pandas DataFrame的新增行列,修改、删除、筛选、判断元素以及转置操作
  51. Add rows and columns, modify, delete, filter, judge elements and transpose operations in pandas dataframe
  52. 虚言妙诀终虚见,面试躬行是致知,Python技术面试策略与技巧实战记录
  53. The interview practice is knowledge, python technology interview strategy and skills of the actual record
  54. 用tqdm和rich为固定路径和目标的python算法代码实现进度条
  55. Using tqdm and rich as the fixed path and target of Python algorithm code to realize the progress bar
  56. 我来记笔记啦-Django开发流程与配置
  57. Let me take notes - Django development process and configuration
  58. python数据类型的强制转换
  59. Django报错:'Key 'id' not found in 'xxx'. Choices are: xxx'
  60. Python400集大型视频,从正确的方向出发学习,全套完整送给大家