如何在Django中间件中处理异常?

时间:2019-05-23 09:36:05

标签: python django django-rest-framework middleware

我在正确处理Django中间件中的异常时遇到问题。 我的例外:

from rest_framework.exceptions import APIException
from rest_framework.status import HTTP_403_FORBIDDEN
class MyProfileAuthorizationError(APIException):    
    def __init__(self, msg):
        APIException.__init__(self, msg)
        self.status_code = HTTP_403_FORBIDDEN
        self.message = msg

还有我的中间件:

class PatchRequestUserWithProfile:
def __init__(self, get_response):
    self.get_response = get_response

def __call__(self, request, *args, **kwargs):
    patch_request_for_nonanon_user(request)
    if not request.user.profile:
        raise MyProfileAuthorizationError("You are not allowed to use this profile.")

    response = self.get_response(request)
    return response

并且此异常抛出500而不是403。我该如何解决?

3 个答案:

答案 0 :(得分:3)

尝试返回HttpResponseForbidden响应,而不是引发异常

from django.http import HttpResponseForbidden


class PatchRequestUserWithProfile:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request, *args, **kwargs):
        patch_request_for_nonanon_user(request)
        if not request.user.profile:
            return HttpResponseForbidden("You are not allowed to use this profile.")

        response = self.get_response(request)
        return response

答案 1 :(得分:1)

我认为您应该使用permissions而不是使用中间件:

et-xmlfile==1.0.1
jdcal==1.4.1
openpyxl==2.6.2
pkg-resources==0.0.0

并将其添加到DEFAULT_PERMISSION_CLASSES中,以使其可用于每个API视图。

from rest_framework import permissions

class CustomAccessPermission(permissions.BasePermission):
    message = 'You are not allowed to use this profile.'

    def has_permission(self, request, view):
       if not request.user.profile:
           return False
       return True

答案 2 :(得分:1)

尝试使用以下例外:

from rest_framework.exceptions import APIException

class MyProfileAuthorizationError(APIException):
    status_code = 403
    default_detail = 'You are not allowed to use this profile'
    default_code = 'forbidden'

我认为您无法做到这一点,请阅读以下内容:https://groups.google.com/forum/#!topic/django-developers/-ncPqVzF8W8