Django的路由是怎么回事在这里不再赘述,这里主要说一下include()
的用法,以及装配路由的一点技巧。
include()
include
主要有下面两种用法:
include(module, namespace=None)
include(pattern_list)
用法一:include(module, namespace=None)
这种用法中,参数module
类型为str|object
,它的值是一个模块,或者是一个模块路径,可以正常定位这个模块,
include
函数会自动加载module
中的urlpatterns
属性。
urlpatterns
是一个列表,类型为list[RegexURLResolver|RegexURLPattern]
。
例如:
1 2 3 4 5 6 7 8 9
| urlpatterns = [ url(r'^community/', include('django_website.aggregator.urls')), url(r'^contact/', include('django_website.contact.urls')), url(r'^author-polls/', include('polls.urls', namespace='author-polls')), url(r'^publisher-polls/', include('polls.urls', namespace='publisher-polls')), ]
|
用法二:include(pattern_list)
参数pattern_list
是一个列表,类型为list[RegexURLResolver|RegexURLPattern]
。
例如:
1 2 3 4 5 6 7 8
| polls_patterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'), ]
urlpatterns = [ url(r'^polls/', include(polls_patterns)), ]
|
自动装配路由
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
from importlib import import_module
from django.conf import settings from django.conf.urls import url, include
urlpatterns = []
_c_urlpatterns, _p_urlpatterns = [], [] for app in settings.INSTALLED_APPS: if app.startswith('django.contrib'): continue try: urlconf_module = import_module(app + '.urls') urlpatterns += getattr(urlconf_module, 'urlpatterns', []) _c_urlpatterns += getattr(urlconf_module, 'c_urlpatterns', []) _p_urlpatterns += getattr(urlconf_module, 'p_urlpatterns', []) except ImportError: pass
urlpatterns += [ url(r'^cs/(?P<c_id>\w{1,32})', include(_c_urlpatterns)), url(r'^ps/(?P<p_id>\w{1,32})', include(_p_urlpatterns)), ]
|