当前位置:   article > 正文

django 类视图_django drf viewpy文件中同时包含函数视图类视图

django drf viewpy文件中同时包含函数视图类视图
  • 类视图 实现

    • 以函数的方式定义的视图称为函数视图
    • 在Django中还可以通过类来定义一个视图,称为类视图
    • 类视图 的使用

      1. 定义一个类,继承Django提供的View

        1. from django.views.generic import View
        2. class PostView(View):
        3. def get(self, request):
        4. """get请求: 显示发帖界面"""
        5. return render(request, 'post2.html')
        6. def post(self, request):
        7. """post请求: 执行发帖操作"""
        8. # 代码简略
        9. return HttpResponse('执行发帖操作')
      2. 调用类视图的 as_view() 方法配置url

        1. urlpatterns = [
        2. ...
        3. # 类视图注册
        4. url(r'^post2$', views.PostView.as_view()),
        5. ]
  • 类视图优点:对于函数视图代码可读性和复用性更好

视图中使用装饰器

一、在函数视图中使用装饰器

需求:实现禁止ip黑名单访问发帖界面。 解决:可以通过在视图函数中使用装饰器实现,如下

  1. 为函数视图定义一个装饰器(在设计装饰器时,基本都以函数视图作为考虑的被装饰对象)

    1. def check_ip(view_fun):
    2. """装饰器:禁止黑名单ip访问"""
    3. def wrapper(request, *args, **kwargs):
    4. # 在视图函数执行前做额外的操作:
    5. # 禁止ip黑名单访问
    6. IP = request.META.get('REMOTE_ADDR')
    7. if IP in ['192.168.210.160']:
    8. return HttpResponse('IP禁止访问')
    9. return view_fun(request, *args, **kwargs)
    10. return wrapper
  2. 给视图函数进行装饰

    1. @check_ip
    2. def post(request):
    3. """GET请求: 显示发帖界面"""
    4. return render(request, 'post.html')

    或者:也可以在URL中,通过方法调用的方式添加装饰器

    1. urlpatterns = [
    2. ...
    3. # 发帖功能
    4. url(r'^post$', check_ip(views.post))
    5. ]
    • 注意:这种添加装饰器的方式代码可读性差,不建议使用

 

二、类视图使用装饰器

(一)在路由中添加装饰器

类似如下,装饰器添加到路由中,则类视图中所有的方法都使用了装饰器,但可读性差,不建议使用。

  1. urlpatterns = [
  2. ...
  3. # 发帖功能
  4. url(r'^post2$', check_ip(views.PostView.as_view()))
  5. ]

(二)在类视图的方法中添加

  • 注意:针对函数定义的装饰器,不能直接应用到类视图的方法中,因为少了一个self参数
  • 解决:可以使用method_decorator装饰器,为函数装饰器补充第一个self参数,使它可以应用到类的方法中。

(1) 给类视图的特定的方法添加装饰器:

  1. class PostView(View):
  2. def get(self, request):
  3. return render(request, 'post2.html')
  4. @method_decorator(check_ip)
  5. def post(self, request):
  6. return HttpResponse('处理发帖操作')

(2)给类视图的所有方法应用装饰器:

  1. class PostView(View):
  2. @method_decorator(check_ip)
  3. def dispatch(self, request, *args, **kwargs):
  4. return super().dispatch(request, *args, **kwargs)
  5. def get(self, request):
  6. return render(request, 'post2.html')

(3)另一种添加装饰器的方式:在类上面添加装饰器,指定对哪个方法进行装饰

  1. @method_decorator(check_ip, name='get')
  2. class PostView(View):
  3. def get(self, request):
  4. return render(request, 'post2.html')
  5. def post(self, request):
  6. return HttpResponse('处理发帖操作')
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/451186
推荐阅读
相关标签
  

闽ICP备14008679号