自定义django class based view 的一个例子

摘要: Django  从 1.3 版本开始进引入了 class based view  的方式,以这种方式处理视图,可以在一些基类中写一些公用方法。我查看 Django 相关文档,感觉有点麻烦。其实如果要将现有的基于 function  的 view 变成 class based  view 应该是比较简单的。完全可以自定义个实现。虽然这不是 django 所要求的方式,但对我来说,这样的改动也许是最小的

Django 从 1.3 版本开始进引入了 class based view 的方式,以这种方式处理视图,可以在一些基类中写一些公用方法。我查看 Django 相关文档,感觉有点麻烦。其实如果要将现有的基于 function 的 view 变成 class based view 应该是比较简单的。完全可以自定义个实现。虽然这不是 django 所要求的方式,但对我来说,这样的改动也许是最小的。举个例子
原来的处理方法如下,这是基于 function 的 view

    def index(self, request, *args, **kwargs):
        return render_to_response('index.html',{},context_instance=RequestContext(request))


    def get(self, request, *args, **kwargs):
        print 'execute get methos'
        print kwargs
        context = {}
        return render_to_response('get.html',context,context_instance=RequestContext(request))


url 的配置:
urlpatterns = patterns('',
    url(r'^$', views.index),
    url(r'^restview/(?P\d{1,15}).html$',views.get ),
    url(r'^restview/head.html$',views.head ),     
)


以上是传统的配置方式,如果要变成 class based view 最简单的方法是什么样的呢,就目前来说,我觉得如下方法或许是最简单的,改动也最小的. 总结为如下:
视图view class 的代码
'''
Created on 2014-5-22
@author: Administrator
'''
from django import http
from django.shortcuts import render_to_response
from django.template.context import RequestContext

class RestView(object):
    methods = ('GET', 'HEAD', 'INDEX')

    @classmethod
    def dispatch(cls, request, *args, **kwargs):       
        print kwargs
        exec_method = kwargs.get('method','')
        resource = cls()
        if exec_method.lower() not in (method.lower() for method in resource.methods):
            return http.HttpResponseNotAllowed(resource.methods)
        try:
            method = getattr(resource, exec_method.lower())
        except AttributeError:
            raise Exception("View method `%s` does not exist." % exec_method.lower())
        if not callable(method):
            raise Exception("View method `%s` is not callable." % exec_method.lower())
        return method(request, *args, **kwargs)
    
    def index(self, request, *args, **kwargs):
        return render_to_response('index.html',{},context_instance=RequestContext(request))


    def get(self, request, *args, **kwargs):
        print 'execute get methos'
        print kwargs
        context = {}
        return render_to_response('get.html',context,context_instance=RequestContext(request))

    def head(self, request, *args, **kwargs):
        print 'execute head method'
        response = self.get(request, *args, **kwargs)
        response.content = 'head method testing'
        return response


同样 urls.py 的配置也要相应改变
from django.conf.urls import patterns, include, url
from views import RestView
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
    url(r'^$', RestView.dispatch, {"method":"index"}),
    url(r'^restview/(?P\d{1,15}).html$', RestView.dispatch, {"method":"get"} ),
    url(r'^restview/head.html$', RestView.dispatch, {"method":"head"} ),   
  
)


在这样的配置之后,运行程序,可以看到如下界面,说明成功运行,并且找到各自的方法,而且改动并不大,只是将原来的方法放到一个类中就可以了。



测试程序代码下载:
customize django class based view sample code

上一篇: 几张图了解django class base view 的响应流程
下一篇: 如何用 python,Djano 生成 SEO 友好的 URL, 包含中文处理
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号