Django basis of route distribution

Django's routing layer

A role, routing

In fact, request routing and address mapping between the view function, if the site compared to a book, then the route is like this book directory, the default configuration of routing in Django in urls.py in.

Second, the simple routing configuration

# urls.py
from django.conf.urls import url

# urlpatterns(路由表):由一条条映射关系组成
urlpatterns = [
    url(regex, view, kwargs=None, name=None),  # ulr本质是一个函数
]

# regex: 正则表达式,用来匹配url地址的路径部分 例如:http://127.0.0.1:8000/index/匹配的部# 分为 index/
# view: 通常为一个视图函数,用来处理业务逻辑
# kwargs: 略(用法详见有名分组)
# name: 略(用法详见反向解析)

note:

There is a parameter in the configuration file settings.py APPEND_SLASH, the two parameter values ​​True or False. When APPEND_SLASH = True (if the configuration is not the configuration file, the default value is True APPEND_SLASH), and the address path portion url is not requested by the user ends with /. So when this url not match the time, Django will add after the path / to go to match the routing table.

Third, grouping

Grouping mainly to make the background of the url get parameters. In Django there are two groupings, namely: the unknown and well-known grouping grouping.

3.1 anonymous group

# urls.py
from django.conf.urls import url

urlpatterns = [
    # 下述正则表达式会匹配url地址的路径部分为:index/数字/,匹配成功的分组部分会以位置参数的形式传给视图函数,有几个分组就传几个位置参数(小括号内为参数的值)
    url(r'^index/(\d+)/$', views.index),
]

3.2 famous grouping

# urls.py
from django.conf.urls import url

urlpatterns = [
    # 该正则会匹配url地址的路径部分为:article/数字/,匹配成功的分组部分会以关键字参数(article_id=匹配成功的数字)的形式传给视图函数,有几个又名分组就会传几个关键字参数
    url(r'^index/(?P<index_id>\d+)$', views.index),
]

to sum up:

Known and unknown packets are packets in order to obtain the parameters of the path, and the view itself, except that the position of unknown points in the form of parameters passed in the form of keywords known packet transfer parameters.

Note: nameless grouping and famous grouping do not mix! ! ! ! ! !

Fourth, route distribution

To be continued ......

Guess you like

Origin www.cnblogs.com/17vv/p/11688453.html