Django中project下的url引入(include)app下的url

今天进行django的回炉,发现django官方文档中开始创建django项目时候,项目的url除了在项目目录下的urls.py中创建外,还引进(include)了app中的urls.py,这怎么理解?

官方文档中给出了:

Whenever Django encounters include(), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.

也就是说,在接收http请求时,url首先与项目下根目录下的urls.py中的字段进行比较,如果有符合的,再从该条目中include的url进行深度匹配。

有点类似于路由器ip。

看个例子:

目录:

mysite:

    -mysite

        -urls.py

    -myapp

        -views.py

        -models.py

        -urls.py

首先,myapp/urls.py

# coding:utf8
from django.conf.urls import include, url
import views
urlpatterns = [
    url(r'^$', views.index,name='index'),
    url(r'login',views.login,name='login'),
]

然后,mysite/urls.py

from django.conf.urls import include, url
from django.contrib import admin


urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^cislab/',include('cislab.urls')),
]


进行访问,/cislab/---对应index

/cislab/login ----对应login。


你可能感兴趣的:(Python)