Django异常处理的推荐方式Http404

一般我们在定义视图的时候,会做各种数据校验,并进行捕获后以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)

验证结果:

posted @ 2020-07-12 15:04  小公瑾  阅读(1182)  评论(0编辑  收藏  举报