Django路由系统
1、单一路由对应
1 url(r'^index$', views.index),
2、基于正则的路由
1 url(r'^index/(\d*)', views.index), 2 url(r'^manage/(?P<name>\w*)/(?P<id>\d*)', views.manage),
3、添加额外的参数,默认的参数
1 url(r'^manage/(?P<name>\w*)', views.manage,{'id':333}),
4、为路由映射设置名称
1 url(r'^home', views.home, name='h1'), 2 url(r'^index/(\d*)', views.index, name='h2'),
5、根据app对路由规则进行分类
1 url(r'^web/',include('web.urls')),
动态url:
1 urlpatterns = [ 2 url(r'^admin/', admin.site.urls), 3 4 #url----function 5 ''' 6 url(r'^index/',index ), 7 url(r'^Login/',login ), 8 #配置动态的URL,因为此时不确定我会产生多少条url,此时在函数中需要加上一个捕获的参数,id,用来捕获用户的id 9 #尖括号里面的值需要与业务逻辑层次上对应,模板格式 10 url(r'^list/(?P<name>\d*)/(?P<id>\d*)/',list ), 11 #设置默认值 12 url(r'^list/(?P<name>\d*)/',list ,{'id':222}), 13 ''' 14 15 16 ]
分类的url:
1 urlpatterns = [ 2 url(r'^admin/', admin.site.urls), 3 4 5 6 7 #url----file 8 #file-----url>function 类似于路径映射,本来是单纯的由jango里面的urls(全局的url)统一的配置路由信息,但是如果我的app多了之后这就会显得有点乱,所以此时可以指定URL路径,由各自的APP去执行url,每个路径多加了一个分类的路径 9 url(r'^ad/', include('ad.urls')), 10 url(r'^web/',include('web.urls')), 11 12 ]
6、通过反射机制,为django开发一套动态的路由系统
在urls.py里定义分类正则表达式
1 from django.conf.urls import patterns, include, url 2 from django.contrib import admin 3 from DynamicRouter.activator import process 4 5 urlpatterns = patterns('', 6 # Examples: 7 # url(r'^$', 'DynamicRouter.views.home', name='home'), 8 # url(r'^blog/', include('blog.urls')), 9 10 url(r'^admin/', include(admin.site.urls)), 11 12 13 ('^(?P<app>(\w+))/(?P<function>(\w+))/(?P<page>(\d+))/(?P<id>(\d+))/$',process), 14 ('^(?P<app>(\w+))/(?P<function>(\w+))/(?P<id>(\d+))/$',process), 15 ('^(?P<app>(\w+))/(?P<function>(\w+))/$',process), 16 ('^(?P<app>(\w+))/$',process,{'function':'index'}), 17 )
在同目录下创建activater.py
1 #!/usr/bin/env python 2 #coding:utf-8 3 4 from django.shortcuts import render_to_response,HttpResponse,redirect 5 6 7 def process(request,**kwargs): 8 '''接收所有匹配url的请求,根据请求url中的参数,通过反射动态指定view中的方法''' 9 10 app = kwargs.get('app',None) 11 function = kwargs.get('function',None) 12 13 try: 14 appObj = __import__("%s.views" %app) 15 viewObj = getattr(appObj, 'views') 16 funcObj = getattr(viewObj, function) 17 18 #执行view.py中的函数,并获取其返回值 19 result = funcObj(request,kwargs) 20 21 except (ImportError,AttributeError),e: 22 #导入失败时,自定义404错误 23 return HttpResponse('404 Not Found') 24 except Exception,e: 25 #代码执行异常时,自动跳转到指定页面 26 return redirect('/app01/index/') 27 28 return result