URL pattern to match n terms
I'm trying to write a Django URL pattern that matches 1 to n strings separated by slashes. It should match any of these and pass each term to the view:
foo.com/apples
foo.com/apples/oranges foo.com/oranges/apples/lizards/google_android/adama
In Django I could just pass the entire thing to开发者_如何学运维 a view as a string and parse it manually, but I was curious if there is some kind of regex to do this more elegantly.
A regex will always match one substring, not multiple string parts, so it's not possible for you to get a list instead of a single match.
You should parse the words manually:
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("/")))
Depending on your use case, each word might have a fixed meaning, such as a date or product category. Then you can probably make some of them optional like so:
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))
With multiple arguments, it is probably easier to use GET parameters rather than parsing the URL. These are automatically converted into a list where necessary:
http://foo.com/?arg=apple&arg=orange&arg=lizard
with the urlconf of just:
(r'^$', myView),
in the view you just do:
args = request.GET.getlist('arg')
and args
will now be a list of all the arg
parameters.
精彩评论