ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
## FBV和CBV ### FBV Function Base View 处理方法是一个函数 ~~~ urlpatterns = patterns('', url(r'^home/$', 'learn.views.index'), # error page url(r'^\w+/$', 'learn.views.errorpage'), ) ~~~ ### CBV Class Base View 处理方法是一个类,使用`className.as_view()`,进行指定。 ~~~ urlpatterns = patterns('', url(r'^home/', views.Home.as_view()), # error page url(r'^\w+/$', 'learn.views.errorpage'), ) ~~~ views中的类,分别处理不同方式的请求,在处理请求之前(pre-handler)和之后(post-handler)可定义不同的处理。类似于对请求的装饰器。 ~~~ class Home(View): # 处理进来的请求,get还是post, 通过反射找到各种方法 def dispatch(self, request, *args, **kwargs): print('before') result = super(Home, self).dispatch(request, *args, **kwargs) print('after') return result def get(self, request): print(request.method) return render(request, 'home.html') def post(self, request): print(request.method) return render(request, 'home.html') ~~~ --- 路由定义URL(网址)对应的视图函数 (即规定 访问什么网址对应什么内容) * 静态路由 * 动态路由 * 路由分发 多级URL * 自定义路由 ### URL配置 Django 1.7.x 及以下,使用`字符串`方式引用视图函数 [demo下载][1] ```python #coding: utf-8 from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # 路由分发 url(r'^admin/', include(admin.site.urls)), # 静态路由 url(r'^$', 'learn.views.index'), url(r'^home/$', 'learn.views.index'), # 动态路由 url(r'^blog/\w*/?$', 'learn.views.blog'), ## 通过位置获取动态路由中的参数 url(r'^add/(\d+)/(\d+)/$', 'learn.views.add'), ## 通过变量名获取动态路由中的参数 url(r'^plus/(?P<first_number>\d+)/(?P<second_number>\d+)/$', 'learn.views.plus'), # error page url(r'^\w+/$', 'learn.views.errorpage'), ) ``` Django 1.8.x及以上,Django 官方鼓励(或说要求)先引入,再使用 [demo下载][2] ```python from django.conf.urls import include, url from django.contrib import admin from learn import views as learn_views urlpatterns = [ # 路由分发 url(r'^admin/', include(admin.site.urls)), url(r'^admin/', include('app.urls')), # 静态路由 url(r'^$', learn_views.index), url(r'^home/$', learn_views.index), # 动态路由 url(r'^blog/\w*/?$', learn_views.blog), ## 通过位置获取动态路由中的参数 url(r'^add/(\d+)/(\d+)/$', learn_views.add), ## 通过变量名获取动态路由中的参数 url(r'^plus/(?P<first_number>\d+)/(?P<second_number>\d+)/$', learn_views.plus), # error page url(r'^\w+/$', learn_views.errorpage), ] ``` [1]:http://files.cnblogs.com/files/hiyang/demo_url_view_165.tar.gz [2]:http://files.cnblogs.com/files/hiyang/demo_url_view_181.tar.gz