我可以覆盖rest_framework权限类中的http状态吗?

Pit*_*all 4 django django-rest-framework

我正在尝试创建一个继承自 的自定义权限类permissions.BasePermission。我知道您可以覆盖message自定义消息的属性,但是 http 状态也可以被覆盖吗?我想针对过期链接返回 410。不确定我是否试图创造一种意想不到的行为。

或者也许我的逻辑有更好的地方?基本上我想做的是向用户发送邀请链接,他们单击该链接并请求获取一些模型数据。如果这个模型数据是 10 多天前创建的,(它确实有一个created_on属性)我想返回 410。我只是之前没有用这个逻辑设计任何东西,对我来说它闻起来像一个权限类,但我可以错误的。

JPG*_*JPG 7

403 比状态代码 410 的Permission Denied错误非常有意义

。除此之外,您无法更改DRF 中的Permission Denied错误的状态代码(以 DRF 方式)。


获取解决方案的解决方法

创建自定义 API 异常类:

from rest_framework.exceptions import APIException
from rest_framework import status


class GenericAPIException(APIException):
    """
    raises API exceptions with custom messages and custom status codes
    """
    status_code = status.HTTP_400_BAD_REQUEST
    default_code = 'error'

    def __init__(self, detail, status_code=None):
        self.detail = detail
        if status_code is not None:
            self.status_code = status_code
Run Code Online (Sandbox Code Playgroud)

在你的许可类中,

from rest_framework import permissions


class FooPermission(permissions.BasePermission):
    def has_permission(self, request, view):
        if some_condition:
            raise GenericAPIException(detail="exception message", status_code=410)
        return True
Run Code Online (Sandbox Code Playgroud)