1. 程式人生 > >Django-2 路由層

Django-2 路由層

args 告訴 ... 需求 his alt convert converter 要求

U RL配置(URLconf)就像Django 所支撐網站的目錄。它的本質是URL與要為該URL調用的視圖函數之間的映射表。

2.1 簡單的路由配置

from django.urls import path,re_path

from app01 import views

urlpatterns = [
re_path(r‘^articles/2003/$‘, views.special_case_2003),
re_path(r‘^articles/([0-9]{4})/$‘, views.year_archive),
re_path(r‘^articles/([0-9]{4})/([0-9]{2})/$‘, views.month_archive),
re_path(r‘^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$‘, views.article_detail),
]

註意: 若要從URL 中捕獲一個值,只需要在它周圍放置一對圓括號。 不需要添加一個前導的反斜杠,因為每個URL 都有。例如,應該是^articles 而不是 ^/articles。 每個正則表達式前面的‘r‘ 是可選的但是建議加上。它告訴Python 這個字符串是“原始的” —— 字符串中任何字符都不應該轉義 示例:

一些請求的例子:

/articles/2005/03/ 請求將匹配列表中的第三個模式。Django 將調用函數views.month_archive(request, ‘2005‘, ‘03‘)。
/articles/2005/3/ 不匹配任何URL 模式,因為列表中的第三個模式要求月份應該是兩個數字。
/articles/2003/ 將匹配列表中的第一個模式不是第二個,因為模式按順序匹配,第一個會首先測試是否匹配。請像這樣自由插入一些特殊的情況來探測匹配的次序。
/articles/2003 不匹配任何一個模式,因為每個模式要求URL 以一個反斜線結尾。
/articles/2003/03/03/ 將匹配最後一個模式。Django 將調用函數views.article_detail(request, ‘2003‘, ‘03‘, ‘03‘)。

2.2 有名分組

上面的示例使用簡單的、沒有命名的正則表達式組(通過圓括號)來捕獲URL 中的值並以位置 參數傳遞給視圖。在更高級的用法中,可以使用命名的正則表達式組來捕獲URL 中的值並以關鍵字 參數傳遞給視圖。 在Python 正則表達式中,命名正則表達式組的語法是(?Ppattern),其中name 是組的名稱,pattern 是要匹配的模式。 下面是以上URLconf 使用命名組的重寫:

from django.urls import path,re_path

from app01 import views

urlpatterns = [
re_path(r‘^articles/2003/$‘, views.special_case_2003),
re_path(r‘^articles/(?P<year>[0-9]{4})/$‘, views.year_archive),
re_path(r‘^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$‘, views.month_archive),
re_path(r‘^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<day>[0-9]{2})/$‘, views.article_detail),
]

這個實現與前面的示例完全相同,只有一個細微的差別:捕獲的值作為關鍵字參數而不是位置參數傳遞給視圖函數。例如:

/articles/2005/03/ 請求將調用views.month_archive(request, year=‘2005‘, month=‘03‘)函數,而不是views.month_archive(request, ‘2005‘, ‘03‘)。
/articles/2003/03/03/ 請求將調用函數views.article_detail(request, year=‘2003‘, month=‘03‘, day=‘03‘)。

2.3 分發

At any point, your urlpatterns can “include” other URLconf modules. This
essentially “roots” a set of URLs below other ones.
‘‘‘

from django.urls import path,re_path,include
from app01 import views

urlpatterns = [
re_path(r‘^admin/‘, admin.site.urls),
re_path(r‘^blog/‘, include(‘blog.urls‘)),
]

2.4 反向解析

在使用Django 項目時,一個常見的需求是獲得URL 的最終形式,以用於嵌入到生成的內容中(視圖中和顯示給用戶的URL等)或者用於處理服務器端的導航(重定向等)。人們強烈希望不要硬編碼這些URL(費力、不可擴展且容易產生錯誤)或者設計一種與URLconf 毫不相關的專門的URL 生成機制,因為這樣容易導致一定程度上產生過期的URL。 在需要URL 的地方,對於不同層級,Django 提供不同的工具用於URL 反查:

  1. 在模板中:使用url 模板標簽。
  2. 在Python 代碼中:使用from django.urls import reverse()函數 urls.py:
from django.conf.urls import url

from . import views

urlpatterns = [
#...
re_path(r‘^articles/([0-9]{4})/$‘, views.year_archive, name=‘news-year-archive‘),
#...
]

在模板中:

<a href="{% url ‘news-year-archive‘ 2012 %}">2012 Archive</a>

<ul>
{% for yearvar in year_list %}
<li><a href="{% url ‘news-year-archive‘ yearvar %}">{{ yearvar }} Archive</a></li>
{% endfor %}
</ul>

在python中:

from django.urls import reverse
from django.http import HttpResponseRedirect

def redirect_to_year(request):
# ...
year = 2006
# ...
return HttpResponseRedirect(reverse(‘news-year-archive‘, args=(year,))) # 同redirect("/path/")

當命名你的URL 模式時,請確保使用的名稱不會與其它應用中名稱沖突。如果你的URL 模式叫做comment,而另外一個應用中也有一個同樣的名稱,當你在模板中使用這個名稱的時候不能保證將插入哪個URL。在URL 名稱中加上一個前綴,比如應用的名稱,將減少沖突的可能。我們建議使用myapp-comment 而不是comment。

4.5 名稱空間

命名空間(英語:Namespace)是表示標識符的可見範圍。一個標識符可在多個命名空間中定義,它在不同命名空間中的含義是互不相幹的。這樣,在一個新的命名空間中可定義任何標識符,它們不會與任何已有的標識符發生沖突,因為已有的定義都處於其它命名空間中。 由於name沒有作用域,Django在反解URL時,會在項目全局順序搜索,當查找到第一個name指定URL時,立即返回 我們在開發項目時,會經常使用name屬性反解出URL,當不小心在不同的app的urls中定義相同的name時,可能會導致URL反解錯誤,為了避免這種事情發生,引入了命名空間。

project的urls.py:

urlpatterns = [
re_path(r‘^admin/‘, admin.site.urls),
re_path(r‘^app01/‘, include("app01.urls",namespace="app01")),
re_path(r‘^app02/‘, include("app02.urls",namespace="app02")),
]

app01.urls:

urlpatterns = [
re_path(r‘^index/‘, index,name="index"),
]

app02.urls:

urlpatterns = [
re_path(r‘^index/‘, index,name="index"),
]

app01.views

from django.core.urlresolvers import reverse
def index(request):
return HttpResponse(reverse("app01:index"))

app02.views

from django.core.urlresolvers import reverse
def index(request):
return HttpResponse(reverse("app02:index"))

4.6 django2.0版的path

思考情況如下:

urlpatterns = [
re_path(‘articles/(?P<year>[0-9]{4})/‘, year_archive),
re_path(‘article/(?P<article_id>[a-zA-Z0-9]+)/detail/‘, detail_view),
re_path(‘articles/(?P<article_id>[a-zA-Z0-9]+)/edit/‘, edit_view),
re_path(‘articles/(?P<article_id>[a-zA-Z0-9]+)/delete/‘, delete_view),
]

考慮下這樣的兩個問題: 第一個問題,函數 year_archive 中year參數是字符串類型的,因此需要先轉化為整數類型的變量值,當然year=int(year) 不會有諸如如TypeError或者ValueError的異常。那麽有沒有一種方法,在url中,使得這一轉化步驟可以由Django自動完成? 第二個問題,三個路由中article_id都是同樣的正則表達式,但是你需要寫三遍,當之後article_id規則改變後,需要同時修改三處代碼,那麽有沒有一種方法,只需修改一處即可? 在Django2.0中,可以使用 path 解決以上的兩個問題。

基本示例

這是一個簡單的例子:

from django.urls import path  
from . 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>/‘, views.article_detail),  
]

基本規則:

  1. 使用尖括號(<>)從url中捕獲值。
  2. 捕獲值中可以包含一個轉化器類型(converter type),比如使用 捕獲一個整數變量。若果沒有轉化器,將匹配任何字符串,當然也包括了 / 字符。
  3. 無需添加前導斜杠。

以下是根據https://docs.djangoproject.com/en/2.0/topics/http/urls/#example而整理的示例分析表:

技術分享圖片

path轉化器
文檔原文是Path converters,暫且翻譯為轉化器。
Django默認支持以下5個轉化器:

  1. str,匹配除了路徑分隔符(/)之外的非空字符串,這是默認的形式
  2. int,匹配正整數,包含0。
  3. slug,匹配字母、數字以及橫杠、下劃線組成的字符串。
  4. uuid,匹配格式化的uuid,如 075194d3-6885-417e-a8a8-6c931e272f00。
  5. path,匹配任何非空字符串,包含了路徑分隔符

註冊自定義轉化器
對於一些復雜或者復用的需要,可以定義自己的轉化器。轉化器是一個類或接口,它的要求有三點:

  1. regex 類屬性,字符串類型
  2. to_python(self, value) 方法,value是由類屬性 regex 所匹配到的字符串,返回具體的Python變量值,以供Django傳遞到對應的視圖函數中。
  3. to_url(self, value) 方法,和 to_python 相反,value是一個具體的Python變量值,返回其字符串,通常用於url反向引用。

例子:

class FourDigitYearConverter:  
    regex = ‘[0-9]{4}‘  
    def to_python(self, value):  
        return int(value)  
    def to_url(self, value):  
        return ‘%04d‘ % value

使用register_converter 將其註冊到URL配置中:

from django.urls import register_converter, path  
from . import converters, views  
register_converter(converters.FourDigitYearConverter, ‘yyyy‘)  
urlpatterns = [  
    path(‘articles/2003/‘, views.special_case_2003),  
    path(‘articles/<yyyy:year>/‘, views.year_archive),  
    ...  
]

Django-2 路由層