Django's routing layer

Django how to handle requests

When a user requests a page from Django support site, which is determined Python code to be executed by the routing layer:

  1. Root URLconf Django determining module to use. Typically, this is the value ROOT_URLCONF set, but if the incoming HttpRequest object having urlconf property (provided by the middleware), its value is used in place of ROOT_URLCONF settings. .
  2. Django Python module and looks for variable load urlpatterns. Python is a list of urlpatterns django.conf.urls.url () instance.
  3. Django order traverse each URL pattern matching to match immediately after a direct view of performing the corresponding functions.
  4. Once wherein a regular expression match, Django calls will be imported and given view. Passing the view the following parameters:
    • One example of HttpRequest.
    • If the regular expression matches any named group did not return, then the regular expression matching available as positional parameters.
    • Any keyword parameter named group of regular expression matching the composition of any parameters specified by django.conf.urls.url () optional parameters kwargs covering.
  5. If there is no regular expression matching, or in the process during any point raises an exception, Django will call the appropriate error handling view.

Routing layer

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^hello/$',views.hello),
    url(r'^helloword/$',views.helloword),
]

NOTE: The first parameter is a regular expression, according to the matching rule down from a match, a match immediately after the match, the corresponding direct view function performed

网站首页路由
url(r'^$',views.home)
网站不存在页面
url(r'',views.error)

URL () function has four parameters, two are required: regex and View, two optional: kwargs and name

  • regex is a regular expression shorthand, which is a syntax string pattern matching, Django the requested URL matches the sequence from the top of the list of regular expressions until a match to date.

  • When Django view matches a regular expression will call the specified logical view, the above code will call app01 / views.py the hello function.

  • kwargs any keyword parameters can be passed to target a dictionary view.

  • name Name your URL, the url Django used elsewhere, particularly in the template.

A matching routing example:

from django.conf.urls import url
from . import views
urlpatterns = [
    url(r'^articles/2003/$', views.special_case_2003),
    url(r'^articles/([0-9]{4})/$', views.year_archive),
    url(r'^articles/([0-9]{4})/([0-9]{2})/$', views.month_archive),
    url(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$', views.article_detail),
]

Example Request:

  • Request / articles / 2005/03 / matches the third entry in the list. Django will call the function. views.month_archive (request, '2005', '03')
  • / Articles / 2005/3 / URL does not match any pattern, because the third entry in the list require a digital two months.
  • / Articles / 2003 / the first match list mode instead of the second mode, since the mode is the sequential test, the first test to be passed first. Order free to use insert such special circumstances. Here, Django would call the function views.special_case_2003 (request)
  • / Articles / 2003 does not match any of these patterns, because each pattern requires the URL to slash at the end.
  • / Articles / 2003/03/03 / final match mode. Django will call the function. views.article_detail (request, '2003', '03', '03')

Unknown group

The parenthesized regular expression matching to the content as the positional parameters are automatically passed to the function corresponding to the view.

url(r'^hello/(\d+)/',views.hello),  # 匹配一个或多个数字
def hello(request,xxx):
    print(xxx)
    return HttpResponse('hello!')

Famous grouping

The parenthesized regular expression matching to the content as the key parameter is automatically passed to the function corresponding to the view.

url(r'^hello/(?P<year>\d+)/',views.hello),  # 匹配一个或多个数字

def hello(request,year):
    print(year)
    return HttpResponse('hello!')

Note: nameless group and can not be mixed up with the well-known group, but supports more types of form with a match! ! !

不支持
url(r'^test/(\d+)/(?P<year>\d+)/',views.test) # 会报错
无名分组多个
url(r'^test/(\d+)/(\d+)/',views.test),
有名分组多个
url(r'^test/(?P<year>\d+)/(?P<xxx>\d+)/',views.test),

Reverse lookup

If the URL hardcoded URLs, will make the change in the URL (regular), the template (template), view ( views.py , such as a URL jump), model ( models.py , record the access address, etc.) with this URL, must make the appropriate changes, modifications great price, accidentally, some places did not change overnight, can not be used. So it is necessary to dynamically acquire under the name of the corresponding path, this is the so-called reverse analysis URL *, reverse URL matching , reverse lookup URL or URL * simple reversal.

Django provides tools to perform URL reversal, these tools need to match the different layers of the URL:

  • In the template: Use the url template tag.
  • In Python code: using the reverse () function.
  • In a more advanced process model code associated with the URL of the Django example: the a get_absolute_url () method.
from django.shortcuts import reverse	
url(r'^index666/$',views.index,name='index')

前端使用
{% url 'index' %}
{% url '你给路由与视图函数对应关系起的别名' %}

后端使用
reverse('index')
reverse('你给路由与视图函数对应关系起的别名')

receiving the reverse url name as the first argument, we can acquire the code in the URL by the corresponding reverse () (this URL can be used to jump, it may be used to calculate the address of the relevant page), as long as the corresponding url name does not change, do not change the code in the URL.

Unknown Packet reverse lookup

url(r'^test/(\d+)/',views.test,name='list')

前端使用
{% url 'list' 10 %}

后端使用
reverse('list',args=(10,))

示例:
user_list = models.User.objects.all()
url(r'^edit/(\d+)/',views.edit,name='edit')
前端模板语法
{%for user_obj in user_list%}
<a href='{% url 'edit' edit_id %}'></a>
{% endfor %}
视图函数
from django.shortcuts import reverse
def edit(request,edit_id):
	url = reverse('edit',args=(edit_id,))

Famous grouping reverse lookup

前端使用
# 前端有名分组和无名分组都可以用这种形式
{% url 'list' 10 %}
# 下面这个了解即可
{% url 'list' year=10 %}
后端使用
# 后端有名分组和无名分组都可以用这种形式
print(reverse('list',args=(10,)))
# 下面这个了解即可
print(reverse('list',kwargs={'year':10}))

Summary: For reverse lookup famous and anonymous packet of the packet format to adopt a uniform

后端
reverse('list',args=(10,))  # 这里的数字通常都是数据的主键值
前端
{% url 'list' 10 %}

Reverse analysis of the essence: is to get to be able to access a name corresponding to the view function

Route distribution

Django below each app can have its own urls.py routing layer, templates folder, static folder name urls.py project (total route) do not match with the view of the relationship routing function but do routing distribution.

from django.conf.urls import include
	
# 路由分发  注意路由分发总路由千万不要$结尾
url(r'^app01/',include(app01_urls)),
url(r'^app02/',include(app02_urls))

# 在应用下新建urls.py文件,在该文件内写路由与视图函数的对应关系即可
from django.conf.urls import url
from app01 import views
urlpatterns = [
url(r'^index/',views.index)
]

Namespaces

URL namespace can only be found to ensure that the anti-URL, even if the same app use different URL name. It also allows you to have multiple instances of the case of the deployment of anti-check URL in an application. In other words, because multiple instances of a named applications share the same URL, the namespace provides a method of distinguishing these naming URL.

url(r'^app01/',include(app01_urls,namespace='app01')),
url(r'^app02/',include(app02_urls,namespace='app02'))

app01.urls.py:
from django.conf.urls import url
from app01 import views
urlpatterns = [
url(r'^index/',views.index,name='index')
]
	
app02.urls.py:
from django.conf.urls import url
from app02 import views
urlpatterns = [
url(r'^index/',views.index,name='index')
]
	
app01.views.py:
reverse('app01:index')
	
app02.views.py:
reverse('app02:index')

The difference between django1.0 and django2.0:

The first argument django2.0 path which does not support regular, what you write will match 100% accurate matching
django2.0 inside re_path corresponds django1.0 inside the url

Although django2.0 inside path does not support regular expressions, but it provides five default converter

str,匹配除了路径分隔符(/)之外的非空字符串,这是默认的形式
int,匹配正整数,包含0。
slug,匹配字母、数字以及横杠、下划线组成的字符串。
uuid,匹配格式化的uuid,如 075194d3-6885-417e-a8a8-6c931e272f00。
path,匹配任何非空字符串,包含了路径分隔符(/)(不能用?)

Custom converter
1. regex
2. Class
3. Register

自定义转换器
class FourDigitYearConverter:
	regex = '[0-9]{4}'
	def to_python(self, value):
		return int(value)
	def to_url(self, value):
		return '%04d' % value  # 占四位,不够用0填满,超了则就按超了的位数来!
register_converter(FourDigitYearConverter, 'yyyy')

PS: the default route matches the data string is

Guess you like

Origin blog.csdn.net/linwow/article/details/91395545