路由系统分发的本质
反向生成redirect跳转url
1.在urls.py中指定url的name
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^index/', views.index, name="INDEX"),
url(r'^login/', views.login),
]
2.在views视图函数中使用reverse指定 INDEX地址
from django.shortcuts import render, HttpResponse, redirect
from django.shortcuts import reverse
def index(request):
return HttpResponse("hello")
def login(request):
# 通过reverse("INDEX") 指向 "INDEX" 别名
return redirect(reverse("INDEX"))
应用url的分发include
1.将包含cmdb应用的url请求,转发给cmdb引用中的urls.py中
from django.conf.urls import url, include
from django.contrib import admin
from app01 import views
urlpatterns = [
# 127.0.0.1:8000/cmdb/xxxx/ cmdb的url 转到cmdb 应用下的urls中
url(r'^cmdb/', include("cmdb.urls")),
]
2.在指定APP的项目中,创建一个 urls.py文件
from django.conf.urls import url
from cmdb import views
urlpatterns = [
# 跳转到该应用中的 views 视图函数中
url(r'^hosts/$', views.hosts),
]
反向生成URL地址,指定namespace
1.将指定app的url跳转,加上namespace="o",指定跳转到哪个应用app
from django.conf.urls import url, include
from django.contrib import admin
from app01 import views
urlpatterns = [
# url(r'^admin/', admin.site.urls),
url(r'^index/', views.index, name="INDEX"),
url(r'^login/', views.login),
url(r'^cmdb/', include("cmdb.urls", namespace="c")),
url(r'^openstack/', include("openstack.urls", namespace="o")),
]
2.在views的视图函数中,使用redirect跳转路径时需要加上前缀"o:hosts"
from django.shortcuts import render, HttpResponse, redirect
from django.shortcuts import reverse
def index(request):
return HttpResponse("hello")
def login(request):
# 登录成功后,跳转到 openstack 应用的 主机列表页面
return redirect(reverse("o:hosts"))
通过 循环的形式 添加URL地址
from django.conf.urls import url
from app01 import views
urlpatterns = [
# url(r'^admin/', admin.site.urls),
# url(r'^index/', views.index, name="INDEX"),
url(r'^login/', views.login),
]
# 通过for 循环将,生成的url 添加到 urlpatterns 中
for i in range(10):
temp = []
for j in range(5):
temp.append(url(r'^inner_%s/' % j, views.login))
v = url(r'^login_%s/' % i, (temp, None, None))
urlpatterns.append(v)
输出,生成的url列表:
^login/
^login_0/ ^inner_0/
^login_0/ ^inner_1/
^login_0/ ^inner_2/
^login_0/ ^inner_3/
^login_0/ ^inner_4/
^login_1/
^login_2/
^login_3/
^login_4/
^login_5/
^login_6/
^login_7/
^login_8/
^login_9/