欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

在Django的URLconf中使用命名組的方法

 更新時間:2015年07月18日 11:19:50   投稿:goldensun  
這篇文章主要介紹了在Django的URLconf中使用命名組的方法,Django是Pyhton各色高人氣開發(fā)框架中最為著名的一個,需要的朋友可以參考下

在我們想要捕獲的URL部分上加上小括號,Django 會將捕獲的文本作為位置參數(shù)傳遞給視圖函數(shù)。 在更高級的用法中,還可以使用 命名 正則表達式組來捕獲URL,并且將其作為關(guān)鍵字參數(shù)傳給視圖。

一個 Python 函數(shù)可以使用關(guān)鍵字參數(shù)或位置參數(shù)來調(diào)用,在某些情況下,可以同時進行使用。 在關(guān)鍵字參數(shù)調(diào)用中,你要指定參數(shù)的名字和傳入的值。 在位置參數(shù)調(diào)用中,你只需傳入?yún)?shù),不需要明確指明哪個參數(shù)與哪個值對應(yīng),它們的對應(yīng)關(guān)系隱含在參數(shù)的順序中。

例如,考慮這個簡單的函數(shù):

def sell(item, price, quantity):
  print "Selling %s unit(s) of %s at %s" % (quantity, item, price)

為了使用位置參數(shù)來調(diào)用它,你要按照在函數(shù)定義中的順序來指定參數(shù)。

sell('Socks', '$2.50', 6)

為了使用關(guān)鍵字參數(shù)來調(diào)用它,你要指定參數(shù)名和值。 下面的語句是等價的:

sell(item='Socks', price='$2.50', quantity=6)
sell(item='Socks', quantity=6, price='$2.50')
sell(price='$2.50', item='Socks', quantity=6)
sell(price='$2.50', quantity=6, item='Socks')
sell(quantity=6, item='Socks', price='$2.50')
sell(quantity=6, price='$2.50', item='Socks')

最后,你可以混合關(guān)鍵字和位置參數(shù),只要所有的位置參數(shù)列在關(guān)鍵字參數(shù)之前。 下面的語句與前面的例子是等價:

sell('Socks', '$2.50', quantity=6)
sell('Socks', price='$2.50', quantity=6)
sell('Socks', quantity=6, price='$2.50')

在 Python 正則表達式中,命名的正則表達式組的語法是 (?P<name>pattern) ,這里 name 是組的名字,而 pattern 是匹配的某個模式。

下面是一個使用無名組的 URLconf 的例子:

from django.conf.urls.defaults import *
from mysite import views

urlpatterns = patterns('',
  (r'^articles/(\d{4})/$', views.year_archive),
  (r'^articles/(\d{4})/(\d{2})/$', views.month_archive),
)

下面是相同的 URLconf,使用命名組進行了重寫:

from django.conf.urls.defaults import *
from mysite import views

urlpatterns = patterns('',
  (r'^articles/(?P<year>\d{4})/$', views.year_archive),
  (r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/$', views.month_archive),
)

這段代碼和前面的功能完全一樣,只有一個細微的差別: 取的值是以關(guān)鍵字參數(shù)的方式而不是以位置參數(shù)的方式傳遞給視圖函數(shù)的。

例如,如果不帶命名組,請求 /articles/2006/03/ 將會等同于這樣的函數(shù)調(diào)用:

month_archive(request, '2006', '03')

而帶命名組,同樣的請求就會變成這樣的函數(shù)調(diào)用:

month_archive(request, year='2006', month='03')

使用命名組可以讓你的URLconfs更加清晰,減少搞混參數(shù)次序的潛在BUG,還可以讓你在函數(shù)定義中對參數(shù)重新排序。 接著上面這個例子,如果我們想修改URL把月份放到 年份的 前面 ,而不使用命名組的話,我們就不得不去修改視圖 month_archive 的參數(shù)次序。 如果我們使用命名組的話,修改URL里提取參數(shù)的次序?qū)σ晥D沒有影響。

當然,命名組的代價就是失去了簡潔性: 一些開發(fā)者覺得命名組的語法丑陋和顯得冗余。 命名組的另一個好處就是可讀性強。

相關(guān)文章

最新評論