路由控制器(urls.py)


路由控制器:

from django.urls import path      # 字符串路由
from django.urls import re_path   # 正则路由,会把url地址看成一个正则模式与客户端的请求url地址进行正则匹配

# path和re_path 使用参数一致.仅仅在url参数和接收参数时写法不一样

基本使用:

  • 无名分组:根据位置传参
  • 有名分组:根据关键字传参
from django.contrib import admin
from django.urls import path,re_path
from app01 import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path(r'^articles/2003/$', views.special_case_2003),
    re_path(r'^articles/([0-9]{4})/$', views.year_archive),
    re_path(r'^articles/([0-9]{4})/([0-9]{2})/$', views.month_archive),
    ## 有名分组,根据名称进行分组,后面方便传参
    re_path(r'^articles/(?P[0-9]{4})/(?P[0-9]{2})/$', views.month_archive2),
]

路由分发:

  • 使用路由分发(include),让每个app目录都单独拥有自己的 urls
全局urls配置
from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('app01/',include("app01.urls"))
]

app01.urls配置
from django.urls import path
from app01 import views

urlpatterns = [
    path('',views.index)
]

views.index配置
from django.shortcuts import render

def index(request):
    return render(request,"index.html")

index.html配置



    
    Title



hello index.........


执行结果:

路由转发器:

  • 内置的url转换器并不能满足我们的需求,因此django给我们提供了一个接口可以让我们自己定义自己的url转换器
全局urls配置
from django.contrib import admin
from django.urls import path,register_converter,include
from app01.views import index



class Mobile(object):
    regex="1[3-9]\d{9}"
    def to_python(self,values):
        return values

register_converter(Mobile, "mo")


urlpatterns = [
    path("index/",index)
]

app01.views函数index配置
from django.shortcuts import HttpResponse

def index(request,m):
    print(":::",type(m))
    return HttpResponse(f"hi,{m}用户")

执行结果: