当我在邮递员中不传递标题时,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': {}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句