看下這個(gè) URLconf:
from django.conf.urls.defaults import *from mysite.views import hello, current_datetime, hours_aheadurlpatterns = patterns('', (r'^hello/$', hello), (r'^time/$', current_datetime), (r'^time/plus/(/d{1,2})/$', hours_ahead),)在 URLconf 中的每一個(gè)入口包括了它所關(guān)聯(lián)的視圖函數(shù),直接傳入了一個(gè)函數(shù)對(duì)象。 這就意味著需要在模塊開始處導(dǎo)入視圖函數(shù)。
但隨著 Django 應(yīng)用變得復(fù)雜,它的 URLconf 也在增長,并且維護(hù)這些導(dǎo)入可能使得管理變麻煩。 (對(duì)每個(gè)新的view函數(shù),你不得不記住要導(dǎo)入它,并且采用這種方法會(huì)使導(dǎo)入語句將變得相當(dāng)長。)可以通過導(dǎo)入 views 模塊本身來避免這個(gè)麻煩。 下面例子的URLconf與前一個(gè)等價(jià):
from django.conf.urls.defaults import ***from mysite import views**urlpatterns = patterns('', (r'^hello/$', **views.hello** ), (r'^time/$', **views.current_datetime** ), (r'^time/plus/(d{1,2})/$', **views.hours_ahead** ),)Django 還提供了另一種方法可以在 URLconf 中為某個(gè)特別的模式指定視圖函數(shù): 你可以傳入一個(gè)包含模塊名和函數(shù)名的字符串,而不是函數(shù)對(duì)象本身。 繼續(xù)示例:
from django.conf.urls.defaults import *urlpatterns = patterns('', (r'^hello/$', **'mysite.views.hello'** ), (r'^time/$', **'mysite.views.current_datetime'** ), (r'^time/plus/(d{1,2})/$', **'mysite.views.hours_ahead'** ),)(注意視圖名前后的引號(hào)。 應(yīng)該使用帶引號(hào)的 'mysite.views.current_datetime' 而不是 mysite.views.current_datetime 。)
使用這個(gè)技術(shù),就不必導(dǎo)入視圖函數(shù)了;Django 會(huì)在第一次需要它時(shí)根據(jù)字符串所描述的視圖函數(shù)的名字和路徑,導(dǎo)入合適的視圖函數(shù)。
當(dāng)使用字符串技術(shù)時(shí),你可以采用更簡化的方式:提取出一個(gè)公共視圖前綴。 在我們的URLconf例子中,每個(gè)視圖字符串的開始部分都是``/,造成重復(fù)輸入。 我們可以把公共的前綴提取出來,作為第一個(gè)參數(shù)傳給/ ``函數(shù):
System Message: WARNING/2 (<string>, line 99); backlinkInline literal start-string without end-string.from django.conf.urls.defaults import *urlpatterns = patterns(**'mysite.views'** , (r'^hello/$', **'hello'** ), (r'^time/$', **'current_datetime'** ), (r'^time/plus/(d{1,2})/$', **'hours_ahead'** ),)注意既不要在前綴后面跟著一個(gè)點(diǎn)號(hào)("." ),也不要在視圖字符串前面放一個(gè)點(diǎn)號(hào)。 Django 會(huì)自動(dòng)處理它們。
牢記這兩種方法,哪種更好一些呢? 這取決于你的個(gè)人編碼習(xí)慣和需要。
字符串方法的好處如下:
更緊湊,因?yàn)椴恍枰銓?dǎo)入視圖函數(shù)。
如果你的視圖函數(shù)存在于幾個(gè)不同的 Python 模塊的話,它可以使得 URLconf 更易讀和管理。
函數(shù)對(duì)象方法的好處如下:
更容易對(duì)視圖函數(shù)進(jìn)行包裝(wrap)。 參見本章后面的《包裝視圖函數(shù)》一節(jié)。
更 Pythonic,就是說,更符合 Python 的傳統(tǒng),如把函數(shù)當(dāng)成對(duì)象傳遞。
兩個(gè)方法都是有效的,甚至你可以在同一個(gè) URLconf 中混用它們。 決定權(quán)在你。
新聞熱點(diǎn)
疑難解答
圖片精選