I tryraise PermissionDenied("Anonymous user")在自定义权限函数内,但我写的消息没有显示在api响应中。相反,它显示默认的禁止消息,说您没有权限执行此操作
我的片段在这里:
class CustomPermission(BasePermission):
"""
returns permission based on the request method and slug
"""
def has_permission(self, request,view):
slug = request.resolver_match.kwargs["slug"]
if slug is not None and request.method == 'POST':
if slug == "abc":
user = request.user
if user.is_staff:
return True
if user.is_anonymous:
print("iam here")
raise PermissionDenied("Anonymous user")
elif slug == "mnp":
return True
else:
return True
在上面的代码中,我到达了("iam Here "),但是匿名用户没有打印,而是显示默认消息。
您可以在message属性中更改错误信息:
from rest_framework import permissions
class CustomerAccessPermission(permissions.BasePermission):
message = 'Your message'
def has_permission(self, request, view):
... # return True or False
Docs in: https://www.django-rest-framework.org/api-guide/permissions/#custom-permissions
之后,将调用视图中的permission_denied(self, request, message=None, code=None)
函数,其中message
是您在权限类中声明的属性。
你可以使用它,甚至传递另一个消息:
from rest_framework.exceptions import PermissionDenied
class YourView(...):
permission_classes = [CustomerAccessPermission]
def permission_denied(self, request, message=None, code=None):
raise PermissionDenied(message)