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

Chi*_*fir 2 python django middleware django-rest-framework

我在正确处理 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
Run Code Online (Sandbox Code Playgroud)

还有我的中间件:

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
Run Code Online (Sandbox Code Playgroud)

这个异常抛出 500 而不是 403。我该如何解决?

JPG*_*JPG 8

尝试返回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
Run Code Online (Sandbox Code Playgroud)