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

2024-05-18 15:19:06 发布

您现在位置:Python中文网/ 问答频道 /正文

在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

以及我的中间件:

^{pr2}$

这个异常抛出500而不是403。我该怎么解决呢?


Tags: 中间件djangofromimportselfresthttpinit
3条回答

尝试以下例外情况:

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

尝试返回^{}响应,而不是引发异常

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

我认为您应该使用^{},而不是使用中间件:

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

并将其添加到^{}中,使其可用于每个API视图。在

^{pr2}$

相关问题 更多 >

    热门问题