Django之CBV
2018-10-19 本文已影响33人
CaiGuangyin
CBV,即Class Base View,类基本视图。
在写API时,我们通常都是使用CBV,而非FBV (Function Base View)。
1. cbv遇到要加装饰器时
- 需要先导入
from django.utils.decorators import method_decorator
- 在指定方法上方加
@method_decorator(x1)
,其中x1
是你希望添加的装饰器
import json
from django.shortcuts import render, HttpResponse
from django.utils.decorators import method_decorator
from django.views import View
class AssetView(View):
"""
资产相关接口
"""
@method_decorator(x1)
def get(self, requset, *args, **kwargs):
host_list = ['c1.com', 'c2.com', 'c3.com']
return HttpResponse(json.dumps(host_list))
@method_decorator(x2)
def post(self, request, *args, **kwargs):
info = json.loads(request.body.decode('utf-8'))
print(info)
return HttpResponse('收到了')
2. CBV中免除CSRF认证
需要先导入from django.views.decorators.csrf import csrf_exempt
方式一
直接在视图class上加@method_decorator(csrf_exempt, name='dispatch')
import json
from django.shortcuts import render, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.views import View
# 方式一
@method_decorator(csrf_exempt, name='dispatch')
class AssetView(View):
"""
资产相关接口
"""
def get(self, requset, *args, **kwargs):
host_list = ['c1.com', 'c2.com', 'c3.com']
return HttpResponse(json.dumps(host_list))
def post(self, request, *args, **kwargs):
info = json.loads(request.body.decode('utf-8'))
print(info)
return HttpResponse('收到了')
方式二
在视图class中加入如下段代码:
# 方式二
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request, *args, **kwargs)
示例如下:
import json
from django.shortcuts import render, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.views import View
class AssetView(View):
"""
资产相关接口
"""
# 方式二
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request, *args, **kwargs)
def get(self, requset, *args, **kwargs):
host_list = ['c1.com', 'c2.com', 'c3.com']
return HttpResponse(json.dumps(host_list))
def post(self, request, *args, **kwargs):
info = json.loads(request.body.decode('utf-8'))
print(info)
return HttpResponse('收到了')
3. django rest_framework
- 自动加csrf_exempt
- 页面变好看
- 自动反序列化
from rest_framework.views import APIView
from rest_framework.response import Response
class AssetView(APIView):
def get(self, requset, *args, **kwargs):
host_list = ['c1.com', 'c2.com', 'c3.com']
# return HttpResponse(json.dumps(host_list))
return Response(host_list)
def post(self, request, *args, **kwargs):
# info = json.loads(request.body.decode('utf-8'))
# print(info)
print(request.data) # json格式
return HttpResponse('收到了')