1. 程式人生 > 其它 >達夢資料庫LENGTH_IN_CHAR(物件的長度是否以字元為單位)總結

達夢資料庫LENGTH_IN_CHAR(物件的長度是否以字元為單位)總結

url和path

  Django1.x路由層使用的是url方法

  Django2.x和Django3.x版本中路由層使用的是path方法

    url()第一個引數支援正則

    path() 第一個引數是不支援正則,寫什麼就匹配什麼。

  2.x和3.x還支援re_path,相當於1.x中的url,第一個引數支援正則,不過不推薦

path中的轉換器

  雖然path不支援正則,但是他的內部支援五種轉換器

str,匹配除了路徑分隔符(/)之外的非空字串,這是預設的形式
int,匹配正整數,包含0。
slug,匹配字母、數字以及橫槓、下劃線組成的字串。
uuid,匹配格式化的uuid,如 075194d3
-6885-417e-a8a8-6c931e272f00。 path,匹配任何非空字串,包含了路徑分隔符(/)(不能用?)

  例子

path('articles/<int:year>/<int:month>/<slug:other>/', views.article_detail) 
# 針對路徑http://127.0.0.1:8000/articles/2009/123/hello/,path會匹配出引數year=2009,month=123,other='hello'傳遞給函式article_detail

自定義轉換器

  除了有預設的五個轉換器之外,還支援自定義轉換器

  1、在app01下新建檔案path_ converters.py,檔名可以隨意命名

class MonthConverter:
    regex='\d{2}' # 屬性名必須為regex

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

    def to_url(self, value):
        return value # 匹配的regex是兩個數字,返回的結果也必須是兩個數字

  2、在urls.py中,使用register_converter將其註冊到URL配置中:

from django.urls import path,register_converter
from app01.path_converts import
MonthConverter register_converter(MonthConverter,'mon') from app01 import views urlpatterns = [ path('articles/<int:year>/<mon:month>/<slug:other>/', views.article_detail, name='aaa'), ]

  3、views.py中的檢視函式article_detail

from django.shortcuts import render,HttpResponse,reverse

def article_detail(request,year,month,other):
    print(year,type(year))
    print(month,type(month))
    print(other,type(other))
    print(reverse('xxx',args=(1988,12,'hello'))) # 反向解析結果/articles/1988/12/hello/
    return HttpResponse('xxxx')

  4、測試

# 1、在瀏覽器輸入http://127.0.0.1:8000/articles/2009/12/hello/,path會成功匹配出引數year=2009,month=12,other='hello'傳遞給函式article_detail
# 2、在瀏覽器輸入http://127.0.0.1:8000/articles/2009/123/hello/,path會匹配失敗,因為我們自定義的轉換器mon只匹配兩位數字,而對應位置的123超過了2位