2011-02-28 23 views
0

我正在嘗試編寫一個匹配1到n個字符串的斜槓分隔的Django URL模式。它應與任何這些,每個術語傳遞給視圖:匹配n個字詞的網址格式

foo.com/apples
foo.com/apples/oranges
foo.com/oranges/apples/lizards/google_android/adama

在Django中,我可以將整個視圖作爲字符串傳遞給手動解析,但我很好奇是否有某種正則表達式可以更優雅地執行此操作。

回答

4

正則表達式將始終匹配一個子字符串,而不是多個字符串部分,所以您不可能獲得列表而不是單個匹配。

你應該手工解析的話:

urlpatterns = patterns('', 
    (r'^(?P<words>\w+(/\w+)*)/$', myView), 
) 

def myView(request, words): 
    # The URL path /a/b/ will give you the output [u'a', u'b'] 
    return HttpResponse(str(words.split("/"))) 

根據您的使用情況下,每個字可能有一個固定的含義,如日期或產品類別。然後,你可以可能使他們中的一些,像這樣可選:

urlpatterns = patterns('', 
    (r'^(?P<year>\d\d\d\d)/((?P<month>\d\d)/((?P<day>\d\d)/)?)?$', myView), 
) 

def myView(request, year, month, day): 
    # URL path /2010/ will output year=2010 month=None day=None 
    # URL path /2010/01/ will output year=2010 month=01 day=None 
    # URL path /2010/01/01/ will output year=2010 month=01 day=01 
    return HttpResponse("year=%s month=%s day=%s" % (year, month, day)) 
+0

我懷疑如此。謝謝,只會手動解析 - 我想這不是很糟糕。 – cloudshao 2011-03-01 23:21:26

1

使用多個參數,它可能是更容易使用GET參數,而不是解析URL。這些都將自動轉換成必要的列表:

http://foo.com/?arg=apple&arg=orange&arg=lizard 

用的只是URL配置:在視圖

(r'^$', myView), 

你只是做:

args = request.GET.getlist('arg') 

args現在將是一個所有arg參數的列表。