gpt4 book ai didi

python - 如何在 Django rest 框架中自定义 [Authentication credentials were not provided] 错误消息

转载 作者:行者123 更新时间:2023-12-05 06:56:32 25 4
gpt4 key购买 nike

  • 当我没有在 postman 中传递 header 时,DRF 会给我这条消息。

     {"detail": "Authentication credentials were not provided."}
  • 但我想要一条如下所示的自定义消息。

       {
    "status": False,
    "message": "Authentication credentials were not provided.",
    "data": {}
    }

最佳答案

针对所有请求还是仅针对一个或两个 API 端点?

如果是针对某些 api,请按照 Arakkal Abu 在评论中链接您的方式进行操作。我发现 MyCustomExcpetion 的回答很好。

如果它适用于所有端点,请使用像这样的序列化程序/中间件(JWT 示例):

file: url.py
from rest_framework_jwt.views import ObtainJSONWebToken, refresh_jwt_token

url('auth/', ObtainJSONWebToken.as_view(
serializer_class=CustomJWTSerializer)),


file: serializer.py

from rest_framework import serializers
from rest_framework_jwt.serializers import JSONWebTokenSerializer
from rest_framework_jwt.utils import jwt_encode_handler, jwt_payload_handler

class CustomJWTSerializer(JSONWebTokenSerializer):

def validate(self, attrs):
credentials = {
'email': attrs.get('email'),
'password': attrs.get('password')
}
if all(credentials.values()):
user = authenticate(**credentials)
if user:
payload = jwt_payload_handler(user)
return {
'token': jwt_encode_handler(payload),
'user': user}
else:
return {msg: 'other error msg'}
else:
return {
'status': False,
'message': 'Authentication credentials were not provided.',
'data': {}
}

关于python - 如何在 Django rest 框架中自定义 [Authentication credentials were not provided] 错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65102854/

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