django - DRF 中的自定义未授权错误响应
问题描述
如果任何请求未能验证此视图,用户将获得默认的 Django-Rest 页面。如果出现未经授权的请求,我如何自定义此响应。
@api_view(['GET'])
@authentication_classes([JWTTokenUserAuthentication])
@permission_classes([IsAuthenticated])
def home_view(request):
-----
解决方案
您可以创建一个自定义EXCEPTION_HANDLER
函数,
from rest_framework.views import exception_handler
from rest_framework.exceptions import NotAuthenticated
from rest_framework.response import Response
def custom_exception_handler(exc, context):
if isinstance(exc, NotAuthenticated):
return Response({"custom_key": "custom message"}, status=401)
# else
# default case
return exception_handler(exc, context)
然后,在您的设置中将这个新的自定义功能连接起来,
REST_FRAMEWORK = {
# other settings
"EXCEPTION_HANDLER": "dotted.path.to.the.custom.function"
}
因此,您将得到如下结果,
推荐阅读
- c++ - 无法在 OpenCV 中应用 tensorflow 模型
- javascript - sinon 存根一个空属性
- json - 无法使用 powershell 创建正确的 json 对象
- amazon-web-services - EMR 集群不会因 stepfunction 失败而终止
- jmeter - 100 个用户同时发出 20 个不同 http 请求的 JMeter 测试计划
- apache-camel - Camel ActiveMQ 回复问题
- python - Matplotlib 时间序列热图可视化行修改
- javascript - 使用 Jest 测试 jquery ajax 调用
- javascript - 如何在javascript中从地图中获取最后一个索引和值
- python-3.x - 如何使用内置函数作为参数编写用户定义的函数,该函数具有我想在其上运行循环的参数?