django3.0路由學習


一、路徑的匹配
from django.contrib import admin
from django.urls import path
from index import views

urlpatterns = [
    path('articles/2003/', views.special_case_2003), 
    path('articles/<int:year>/', views.year_archive),
    path('articles/<int:year>/<int:month>/', views.month_archive),
    path('articles/<int:year>/<int:month>/<slug:slug>/', views.article_detail),

]
url.py
from django.http import HttpResponse
def special_case_2003(request):
    return HttpResponse("This is the special 2003")

def year_archive(request,year):
    return HttpResponse("This is year archive,Year number is %d" % year)

def month_archive(request,year,month):
    return HttpResponse("This is month archive,It's %d year %d month" %(year,month))

def article_detail(request,year,month,slug):
    return HttpResponse("This is month articl details,It's %d year, %d month,slug is %s" %(year,month,slug))
view.py
1.由/分開,獲取參數用尖括號,可以指定類型
2.路徑后面一定要有/不然匹配不到任何路徑
3.傳遞給視圖函數view包含的參數有request實例以及路徑中獲取到的參數
4.順序匹配

二、轉換器
尖括號內的東西有以下幾類
  • str,匹配除/的非空字符串,未指定轉換器默認
  • int,匹配整形
  • slug, 匹配任意由 ASCII 字母或數字以及連字符和下划線組成的短標簽
  • uuid,這個不知道干啥的
  • path,匹配包含/的非空字段
path('articles/<path:anythings>/',views.anythings)
def anythings(request,anythings):
    return HttpResponse("match nonthing above,your input is %s" % anythings)

訪問http://127.0.0.1:8000/articles/mylove/hello/check/ 

響應match nonthing above,your input is mylove/hello/check

 

三、自定義轉換器

class FourDigitYearConverter:
    regex = '[0-9]{4}'

    def to_python(self, value):
        return int(value)

    def to_url(self, value):
        return '%04d' % value
converter
 
         
from django.urls import path,register_converter
register_converter(converter.FourDigitYearConverter,'yyyy')

查看register_converter文件可以看到django規定的集中默認的轉換器的規則,regex是匹配到的正則表達值。

to_python 是前段往后端python程序傳的類型或值,可以在這里做特殊轉換

 

四、正則表達式轉換器

path---> re_path

轉換器寫法: (?P<匹配后參數名>正則表達式)

例如:re_path('articles/?P<year>[0-9]{4}/$',views.function)

 

五、include

將同類的url指定到app里的urlconf。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM