赞
踩
类视图 实现
类视图 的使用
定义一个类,继承Django提供的View
类
- from django.views.generic import View
-
- class PostView(View):
-
- def get(self, request):
- """get请求: 显示发帖界面"""
- return render(request, 'post2.html')
-
- def post(self, request):
- """post请求: 执行发帖操作"""
- # 代码简略
- return HttpResponse('执行发帖操作')
调用类视图的 as_view()
方法配置url
- urlpatterns = [
- ...
- # 类视图注册
- url(r'^post2$', views.PostView.as_view()),
- ]
类视图优点:对于函数视图代码可读性和复用性更好
需求:实现禁止ip黑名单访问发帖界面。 解决:可以通过在视图函数中使用装饰器实现,如下
为函数视图定义一个装饰器(在设计装饰器时,基本都以函数视图作为考虑的被装饰对象)
- def check_ip(view_fun):
- """装饰器:禁止黑名单ip访问"""
- def wrapper(request, *args, **kwargs):
- # 在视图函数执行前做额外的操作:
- # 禁止ip黑名单访问
- IP = request.META.get('REMOTE_ADDR')
- if IP in ['192.168.210.160']:
- return HttpResponse('IP禁止访问')
- return view_fun(request, *args, **kwargs)
- return wrapper
给视图函数进行装饰
- @check_ip
- def post(request):
- """GET请求: 显示发帖界面"""
- return render(request, 'post.html')
或者:也可以在URL中,通过方法调用的方式添加装饰器
- urlpatterns = [
- ...
- # 发帖功能
- url(r'^post$', check_ip(views.post))
- ]
(一)在路由中添加装饰器
类似如下,装饰器添加到路由中,则类视图中所有的方法都使用了装饰器,但可读性差,不建议使用。
- urlpatterns = [
- ...
- # 发帖功能
- url(r'^post2$', check_ip(views.PostView.as_view()))
- ]
(二)在类视图的方法中添加
(1) 给类视图的特定的方法添加装饰器:
- class PostView(View):
-
- def get(self, request):
- return render(request, 'post2.html')
-
- @method_decorator(check_ip)
- def post(self, request):
- return HttpResponse('处理发帖操作')
(2)给类视图的所有方法应用装饰器:
- class PostView(View):
-
- @method_decorator(check_ip)
- def dispatch(self, request, *args, **kwargs):
- return super().dispatch(request, *args, **kwargs)
-
- def get(self, request):
- return render(request, 'post2.html')
(3)另一种添加装饰器的方式:在类上面添加装饰器,指定对哪个方法进行装饰
- @method_decorator(check_ip, name='get')
- class PostView(View):
-
- def get(self, request):
- return render(request, 'post2.html')
-
- def post(self, request):
- return HttpResponse('处理发帖操作')
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。