inp*_*ive 5 python django django-rest-framework
DRF 文档提供了有关如何创建自定义权限的明确说明,提供了以下代码示例:
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
Run Code Online (Sandbox Code Playgroud)
默认情况下,当权限检查函数返回时,这会给出以下响应False。
HTTP 403 FORBIDDEN
内容类型:application/json
变化:接受
允许:GET、POST、HEAD、OPTIONS{ "detail": "您无权执行此操作。" }
我想更改上面的“详细信息”部分,提供对开发人员更友好的错误消息。我怎么能做到这一点,确保每次权限检查失败时都显示消息?
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)
Run Code Online (Sandbox Code Playgroud)
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()
Run Code Online (Sandbox Code Playgroud)
因此,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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1569 次 |
| 最近记录: |