gpt4 book ai didi

python - 自定义权限检查失败时的错误消息

转载 作者:行者123 更新时间:2023-11-28 16:34:25 25 4
gpt4 key购买 nike

DRF 文档提供了关于 how to create a custom permission 的明确说明,提供以下代码示例:

from rest_framework import permissions

class BlacklistPermission(permissions.BasePermission):
"""
Global permission check for blacklisted IPs.
"""

def has_permission(self, request, view):
ip_addr = request.META['REMOTE_ADDR']
blacklisted = Blacklist.objects.filter(ip_addr=ip_addr).exists()
return not blacklisted

默认情况下,当权限检查函数返回 False 时,这会给出以下响应。

HTTP 403 FORBIDDEN
Content-Type: application/json
Vary: Accept
Allow: GET, POST, HEAD, OPTIONS

{ "detail": "You do not have permission to perform this action." }

我想更改上面的“详细信息”部分,提供对开发人员更友好的错误消息。我该怎么做才能确保每次权限检查失败时都显示消息?

最佳答案

Class APIView checks permissions via

def check_permissions(self, request):
"""
Check if the request should be permitted.
Raises an appropriate exception if the request is not permitted.
"""
for permission in self.get_permissions():
if not permission.has_permission(request, self):
self.permission_denied(request)

here's permission_denied

def permission_denied(self, request):
"""
If request is not permitted, determine what kind of exception to raise.
"""
if not request.successful_authenticator:
raise exceptions.NotAuthenticated()
raise exceptions.PermissionDenied()

因此,将 exceptions.PermissionDenied 子类化并直接在您的自定义 Permission 类中引发它似乎是完全合理的,例如

class CustomForbidden(APIException):
status_code = status.HTTP_403_FORBIDDEN
default_detail = "Add your custom error message here"


class CustomPermission(permissions.BasePermission):
def has_permission(self, request, view):
if not_allowed:
raise CustomForbidden

关于python - 自定义权限检查失败时的错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28414608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com