5.1、django之类视图

5.1类视图

5.1.1类视图介绍

以函数的方式定义的视图称为函数视图。在Django中也可以使用类来定义一个视图,称为类视图。使用类视图可以将视图对应的不同请求方式以类中的不同方法来区别定义。如:

from django.views.generic import View

class RegisterView(View):
    """类视图:处理注册"""

    def get(self, request):
        """处理GET请求,返回注册页面"""
        return render(request, 'register.html')

    def post(self, request):
        """处理POST请求,实现注册逻辑"""
        return HttpResponse('这里实现注册逻辑')

类视图的好处:

  • 代码可读性好
  • 类视图相对于函数视图有更高的复用性

5.1.2类视图的使用

定义类视图需要继承自Django提供的父类View,可使用from django.views.generic import View或者from django.views.generic.base import View 导入。

配置路由时,使用类视图的as_view()方法来添加:

urlpatterns = [

# 类视图绑定路由 url(r'^register/$', views.RegisterView.as_view()), ]

5.1.3类视图使用装饰器

(1)在url配置中装饰

urlpatterns = [

# url(r'^define_classview/$', views.装饰器名(views.类视图名.as_view())) url(r'^define_classview/$', views.my_decorator(views.DefineClassview.as_view())) ]

此种方式会为类视图中的所有请求方法都加上装饰器行为

(2)在类视图中装饰

在类视图中使用为函数视图准备的装饰器时,不能直接添加装饰器,需要使用method_decorator将其转换为适用于类视图方法的装饰器。

method_decorator装饰器使用name参数指明被装饰的方法

# 为全部请求方法添加装饰器
@method_decorator(my_decorator, name='dispatch')
class DemoView(View):
    def get(self, request):
        print('get方法')
        return HttpResponse('ok')

    def post(self, request):
        print('post方法')
        return HttpResponse('ok')


# 为特定请求方法添加装饰器
@method_decorator(my_decorator, name='get')
class DemoView(View):
    def get(self, request):
        print('get方法')
        return HttpResponse('ok')

    def post(self, request):
        print('post方法')
        return HttpResponse('ok')

如果需要为类视图的多个方法添加装饰器,但又不是所有的方法,可以直接在需要添加装饰器的方法上使用method_decorator

 

from django.utils.decorators import method_decorator

# 为特定请求方法添加装饰器
class DemoView(View):

    @method_decorator(my_decorator)  # 为get方法添加了装饰器
    def get(self, request):
        print('get方法')
        return HttpResponse('ok')

    @method_decorator(my_decorator)  # 为post方法添加了装饰器
    def post(self, request):
        print('post方法')
        return HttpResponse('ok')

    def put(self, request):  # 没有为put方法添加装饰器
        print('put方法')
        return HttpResponse('ok')

5.1.4类视图Mixin扩展类

使用面向对象多继承的特性,可以通过定义父类(作为扩展类),在父类中定义想要向类视图补充的方法,类视图继承这些扩展父类,便可实现代码复用。

定义的扩展父类名称通常以Mixin结尾。注意:在继承多个父类时,需要将View放在最后。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章