一般情況下,使用path即可匹配我們想要的url中的參數(shù)。但是,如果要匹配的過于復(fù)雜,使用path中的轉(zhuǎn)換器無法解決的時候,就要使用到re_path(實則是使用正則匹配?。?/center>
3.re_path正則匹配:
如果不做任何限制,瀏覽器中輸入的ULR的地址參數(shù)可以任意多,只要包括規(guī)定的路徑即可成功匹配!
——比如:re_path('hello',views.test5),
輸入路徑:127.0.0.1:8000/aaahelloaaaa都可成功匹配哦!
如果想限制為何path一樣的效果——URL中的路徑必須一模一樣,否則匹配不到,則需要使用正則語法:
——比如:re_path('^hello/$',views.test5)
,就只有輸入路徑127.0.0.1:8000/hello/才可成功匹配!
Django中實戰(zhàn)使用path和re_path
1.urls.py文件:
"""dj_test URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,re_path #導(dǎo)入re_path,使用正則
from . import views
urlpatterns = [ #主路由
path('admin/', admin.site.urls),
path('test/', views.test), #路徑 關(guān)聯(lián)的視圖
path('test2/name>/int:age>/', views.test2), #變量默認接收的是字符串形式 改變格式是通過轉(zhuǎn)換器 int:age>規(guī)定所接收的類型為int型
re_path('^test3/(?Pbb>[0-9]+)',views.test3) # 注意這個格式:test3是路徑固定參數(shù), bb是可以接受路徑中test3/后面參數(shù)的參數(shù)(任意0-9的數(shù)字)!
]
2.views.py視圖函數(shù)文件:
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
#視圖操作
def test(request): #函數(shù)視圖
return HttpResponse("這里是帥哥")
#url傳參(url參數(shù))
def test2(request,name,age): #函數(shù)視圖
return HttpResponse("我叫%s,今年%s歲"%(name,age))
def test3(request,bb): #函數(shù)視圖
return HttpResponse("哈哈哈")
3.效果:
到此這篇關(guān)于Django零基礎(chǔ)入門之路由path和re_path詳解的文章就介紹到這了,更多相關(guān)Django path re_path內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- 詳解解Django 多對多表關(guān)系的三種創(chuàng)建方式
- 教你pycharm運行Django第一個項目
- Django實現(xiàn)靜態(tài)文件緩存到云服務(wù)的操作方法
- Django動態(tài)展示Pyecharts圖表數(shù)據(jù)的幾種方法
- Django將項目移動到新環(huán)境的操作步驟
- Django零基礎(chǔ)入門之模板變量詳解