1. 程式人生 > 其它 >django框架學習之4:re_path函式匹配路由

django框架學習之4:re_path函式匹配路由

技術標籤:django框架django

程式結構:
urls–藍圖urls—藍圖檢視views:

有時候我們在寫url匹配的時候,想要寫使用正則表示式來實現一些複雜的需求,那麼這時候我們可以使用re_path來實現。re_path的引數和path引數一模一樣,只不過第一個引數也就是route引數可以為一個正則表示式
在寫程式時需要的是,在urls程式中定義正則表示式,book中的urls內容為:

from django.urls import path,re_path
from . import views
from django.urls import converters
# converters:轉換器   是int在裡面定義的
urlpatterns = [ path('<int:book_id>',views.book), # 設定int型的約束 path('book_detail/',views.book_detail), # 正則表示式的方式設定複雜一些的url re_path(r'current_year/(?P<year>\d{4})/(?P<month>\d{2})',views.current_year), #re_path(r'current_mo/(?P<year>\d{4}$)',views.current_year),
# 這裡的r''表示的是字串原本的意思,()表示分組,(?P<year>\d{4})表示給分組起名字然後寫匹配規則 ]

在views中定義current_year

def current_year(request,year,month):
    return HttpResponse('今年是%s年月份是%s' % (year,month))

此時,要訪問該頁面需要訪問url為:

http://127.0.0.1:8000/book/current_year/2020/12

在這裡插入圖片描述
完成