繁体   English   中英

如何在Django Framework中将自定义响应返回给api / rest-auth / login /

[英]How to return customized response to api /rest-auth/login/ in Django Framework

这是示例代码,我想返回一些自定义消息,而不是不返回None。 错误究竟是作为响应对象返回的。

from django.contrib.auth.models import User
from rest_framework import authentication
from rest_framework import exceptions

class ExampleAuthentication(authentication.BaseAuthentication):
    def authenticate(self, request):
        username = request.META.get('X_USERNAME')
        if not username:
            return None

        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            raise exceptions.AuthenticationFailed('No such user')

        return (user, None)

做这样的事情

from rest_framework.response import Response
from rest_framework import status

from django.contrib.auth.models import User
from rest_framework import authentication
from rest_framework import exceptions
from rest_framework.response import Response
from rest_framework import status

class ExampleAuthentication(authentication.BaseAuthentication):
    def authenticate(self, request):
        username = request.META.get('X_USERNAME')
        if not username:
            return Response("some response", status=status.HTTP_400_BAD_REQUEST)

        try:
            user = User.objects.get(username=username)
            return Response("user logged in successfully", status=status.HTTP_200_OK)
        except User.DoesNotExist:
            raise exceptions.AuthenticationFailed('No such user')
            return Response("No such user", status=status.HTTP_404_NOT_FOUND)

这样,您可以发送自定义响应。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM