在DRF中拒绝权限时返回自定义消息 [英] Returning custom message when a permission is denied in DRF

查看:365
本文介绍了在DRF中拒绝权限时返回自定义消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django REST Framework 具有

Django REST Framework has an excellent piece of documentation about permissions. I've been able to use pre-made permission classes and also built my own.

但是,在某些API方法中,权限被拒绝"通用消息对用户而言不是很有帮助.例如,如果用户已通过身份验证但帐户已过期,那么最好让用户知道他的帐户已过期,而不仅仅是权限拒绝错误.

However, there are some API methods in which a "Permission denied" generic message is not very informative for the user. For example, if the user is authenticated but the account has expired, it would be nice to let the user know that his account is expired and not just a permission denied error.

在构建自定义权限类时,根据文档,您将返回TrueFalse.但是,如上所述,我希望向用户显示更多信息.如何做到这一点?

When building custom permission classes, you either return True or False - according to the documentation. But I would like, as said above, to show a more informative message to the user. How to accomplish this?

推荐答案

自DRF 3.2.0起,您仅需添加一条消息属性:

Since DRF 3.2.0, You only have to add a message attribute :

from rest_framework import permissions

class CustomerAccessPermission(permissions.BasePermission):
    message = 'Adding customers not allowed.'

    def has_permission(self, request, view): 

请参阅DRF文档: http://www. django-rest-framework.org/api-guide/permissions/#custom-permissions

这篇关于在DRF中拒绝权限时返回自定义消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆