一般我们在定义视图的时候,会做各种数据校验,并进行捕获后以JsonResponse进行返回,在django中有一种推荐的方式是直接抛出异常,该异常django会自动进行处理,并且程序不会因异常抛出而中断程序
一、引用方式
from django.http import Http404
二、使用方法
示例:
from django.http import JsonResponse, Http404 from django.views import View from django.db import connection from .models import Projects from .serializers import ProjectsModelSerializer class ProjectsPage(View): ‘‘‘ 类视图 ‘‘‘ def get_object(self, pk): try: obj = Projects.objects.get(id__exact=pk) except Exception as e: raise Http404("参数错误") return obj def get(self, request, pk=None): if pk: obj = self.get_object(pk) serializer_obj = ProjectsModelSerializer(instance=obj) return JsonResponse({‘code‘: 0, ‘res‘: "success", ‘msg‘: serializer_obj.data}) else: qs = Projects.objects.all() serializer_obj = ProjectsModelSerializer(instance=qs, many=True) return JsonResponse({‘code‘: 0, ‘res‘: "success", ‘msg‘: serializer_obj.data}, safe=False)
验证结果:
抛出异常后,我们可以发现django项目并没有中断程序