学习Django非常简单,几乎不用花什么精力就可以入门了。配置一个url,分给一个函数处理它,返回response,几乎都没有什么很难理解的地方。

写多了,有些问题才逐渐认识到。比如有一个view比较复杂,调用了很多其他的函数。想要把这些函数封装起来,怎么办?当然,可以用注释#------view------这样将函数隔离开,这种方法太low了,简直是在骗自己,连封装都算不上。

Python是一个面向对象的编程语言,如果只用函数来开发,有很多面向对象的优点就错失了(继承、封装、多态)。所以Django在后来加入了Class-Based-View。可以让我们用类写View。这样做的优点主要下面两种:

  1. 提高了代码的复用性,可以使用面向对象的技术,比如Mixin(多继承)
  2. 可以用不同的函数针对不同的HTTP方法处理,而不是通过很多if判断,提高代码可读性

使用class-based views

如果我们要写一个处理GET方法的view,用函数写的话是下面这样。

function-based view

Python

1

2

3

4

5

6

from django.http import HttpResponse

def my_view(request):

    if request.method == 'GET':

        # <view logic>

        return HttpResponse('result')

如果用class-based view写的话,就是下面这样。

class-based view

Python

1

2

3

4

5

6

7

from django.http import HttpResponse

from django.views import View

class MyView(View):

    def get(self, request):

        # <view logic>

        return HttpResponse('result')

Django的url是将一个请求分配给可调用的函数的,而不是一个class。针对这个问题,class-based view提供了一个as_view()静态方法(也就是类方法),调用这个方法,会创建一个类的实例,然后通过实例调用dispatch()方法,dispatch()方法会根据request的method的不同调用相应的方法来处理request(如get(),post()等)。到这里,这些方法和function-based view差不多了,要接收request,得到一个response返回。如果方法没有定义,会抛出HttpResponseNotAllowed异常。

在url中,就这么写:

urls.py

Python

1

2

3

4

5

6

7

# urls.py

from django.conf.urls import url

from myapp.views import MyView

urlpatterns = [

    url(r'^about/$', MyView.as_view()),

]

类的属性可以通过两种方法设置,第一种是常见的Python的方法,可以被子类覆盖。

设置类的属性

Python

1

2

3

4

5

6

7

8

9

10

11

12

13

from django.http import HttpResponse

from django.views import View

class GreetingView(View):

    greeting = "Good Day"

    def get(self, request):

        return HttpResponse(self.greeting)

# You can override that in a subclass

class MorningGreetingView(GreetingView):

    greeting = "Morning to ya"

第二种方法,你也可以在url中指定类的属性:

在url中设置类的属性

Python

1

2

3

urlpatterns = [

    url(r'^about/$', GreetingView.as_view(greeting="G'day")),

]

使用Mixin

Django中使用Mixin来重用代码,一个View Class可以继承多个Mixin,但是只能继承一个View(包括View的子类),推荐把View写在最右边,多个Mixin写在左边。Mixin也是比较复杂的技术,本文不详细说了,以后写一篇针对Mixin的文章吧。

使用装饰器

在CBV中,可以使用method_decorator来装饰方法。

方法的装饰器

Python

1

2

3

4

5

6

7

8

9

10

from django.contrib.auth.decorators import login_required

from django.utils.decorators import method_decorator

from django.views.generic import TemplateView

class ProtectedView(TemplateView):

    template_name = 'secret.html'

    @method_decorator(login_required)

    def dispatch(self, *args, **kwargs):

        return super(ProtectedView, self).dispatch(*args, **kwargs)

也可以写在类上面,传入方法的名字。

装饰类

Python

1

2

3

@method_decorator(login_required, name='dispatch')

class ProtectedView(TemplateView):

    template_name = 'secret.html'

如果有多个装饰器装饰一个方法,可以写成一个list。例如,下面这两种写法是等价的。

装饰器写成list

Python

1

2

3

4

5

6

7

8

9

10

decorators = [never_cache, login_required]

@method_decorator(decorators, name='dispatch')

class ProtectedView(TemplateView):

    template_name = 'secret.html'

@method_decorator(never_cache, name='dispatch')

@method_decorator(login_required, name='dispatch')

class ProtectedView(TemplateView):

    template_name = 'secret.html'

参考资料

  1. Introduction to class-based views
  2. Django 1.6 最佳实践: 如何正确使用 CBVs (Class-based views)