一、最基础的url映射
urls.py:
1 from django.conf.urls import include, url
2 from django.contrib import admin
3 from app01 import views
4
5 urlpatterns = [
6 url(r'^admin/', admin.site.urls),
7 url(r'^index/$', views.index),
8 ]
1、先从创建的app下的views.py面定义处理数据的函数
2、在urls.py里导入views
3、在urlpatterns里写入一条url与处理函数的l映射关系
4、url映射一般是一条正则表达式,“^” 字符串的开始,“$“ 字符串的结束
5、当写成”^$“时,不输入任何url时不会在返回黄页,而是返回后面函数里对应的页面。一般这一条会写在url的最后。如:
1 url(r'^$', views.index),
二、通过反射机制,为django开发一套动态的路由系统
在urls.py里定义分类正则表达式:
from django.conf.urls import patterns, include, urlfrom django.contrib import adminfrom DynamicRouter.activator import processurlpatterns = patterns('', # Examples: # url(r'^$', 'DynamicRouter.views.home', name='home'), # url(r'^blog/', include('blog.urls')),url(r'^admin/', include(admin.site.urls)), ('^(?P(\w+))/(?P(\w+))/(?P(\d+))/(?P(\d+))/$',process), ('^(?P(\w+))/(?P(\w+))/(?P(\d+))/$',process), ('^(?P(\w+))/(?P(\w+))/$',process), ('^(?P(\w+))/$',process,{'function':'index'}),)
在同目录下创建activater.py:
#!/usr/bin/env python
#coding:utf-8
from django.shortcuts import render_to_response,HttpResponse,redirect
def process(request,**kwargs):
'''接收所有匹配url的请求,根据请求url中的参数,通过反射动态指定view中的方法'''
app = kwargs.get('app',None)
function = kwargs.get('function',None)
try:
appObj = __import__("%s.views" %app)
viewObj = getattr(appObj, 'views')
funcObj = getattr(viewObj, function)
#执行view.py中的函数,并获取其返回值
result = funcObj(request,kwargs)
except (ImportError,AttributeError),e:
#导入失败时,自定义404错误
return HttpResponse('404 Not Found')
except Exception,e:
#代码执行异常时,自动跳转到指定页面
return redirect('/app01/index/')
return result
网友评论