03-带参数的路由 和 re_path

发布时间 2023-03-28 18:35:34作者: 测试圈的彭于晏

带参数的路由

# urls.py

urlpatterns = [
   # 路由不能以斜线 / 开头
    # path 中的第三个参数name是路由的名称,和视图函数参数无关

    # 如果没有指定参数类型,默认字符串类型,可以匹配除 / 和 空字符串之外的字符串
    # 首页
    path('', views.index, name="index"),

    # 在path中使用<参数名>表示所传参数,视图函数中的参数名必须和<>中参数名一致
    # int: 匹配0和正整数,视图函数的参数将得到一个整形值
    # 可以多个路由对应一个视图函数
    path('show/', views.show, name="show1"),
    path('show/<int:age>/', views.show, name="show"),

    # slug: 匹配由数字,字母,-和_组成的字符串参数
    path('list/<slug:name>/', views.list_user, name="list"),

    # path: 匹配任何非空字符串,包括 / ,如果有多个参数,path类型必须在最后一个
    path('access/<path:path>', views.access, name="access"),

    # string 默认参数类型
    path('change/<name>/',views.change_name,name='change'),

# views.py
def index(request):
    return HttpResponse("首页")


def show(request, age=0):
    print(type(age))
    return HttpResponse(str(age))


def list_user(request, name):
    print(type(name))
    return HttpResponse(name)


def access(request, path):
    # path可以包含任何字符,包含 /
    return HttpResponse(path)

def change_name(request,name):
    return HttpResponse(name)

re_path

 # re_path和path最大区别就是匹配是 正则模式串
 re_path(r'^tel/(1[3-9]\d{9})/$',views.get_phone,name="phone"),

 # 命名组,视图函数 get_tel中的参数名必须叫 tel
 re_path(r'^tell/(?P<tel>\d{8})/$',views.get_tel,name="tel")
def get_phone(request, phone):
    return HttpResponse(phone)

def get_tel(request, tel):
    return HttpResponse(tel)