Home >Backend Development >Python Tutorial >在Django的URLconf中使用多个视图前缀的方法

在Django的URLconf中使用多个视图前缀的方法

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-06 11:13:571138browse

在实践中,如果你使用字符串技术,特别是当你的 URLconf 中没有一个公共前缀时,你最终可能混合视图。 然而,你仍然可以利用视图前缀的简便方式来减少重复。 只要增加多个 patterns() 对象,象这样:

旧的:

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'),
  (r'^tag/(\w+)/$', 'weblog.views.tag'),
)

新的:

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'),
)

urlpatterns += patterns('weblog.views',
  (r'^tag/(\w+)/$', 'tag'),
)

整个框架关注的是存在一个名为 urlpatterns 的模块级别的变量。如上例,这个变量可以动态生成。 这里我们要特别说明一下,patterns()返回的对象是可相加的,这个特性可能是大家没有想到的。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn