Python 如何在Django框架中返回对api/rest auth/login/的定制响应
这里是示例代码,我想返回一些自定义消息,而不是不返回任何消息。作为返回的响应对象,错误到底是什么Python 如何在Django框架中返回对api/rest auth/login/的定制响应,python,django,Python,Django,这里是示例代码,我想返回一些自定义消息,而不是不返回任何消息。作为返回的响应对象,错误到底是什么 from django.contrib.auth.models import User from rest_framework import authentication from rest_framework import exceptions class ExampleAuthentication(authentication.BaseAuthentication): def auth
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)
通过这种方式,您可以发送自定义响应。您是否可以再告诉我一点您想要实现的目标,以及您是否正在使用第三方库?如果不是的话,我建议你不要使用自定义身份验证,因为有一些非常好的库,你可以根据自己的需要覆盖它们。我可以在这个类中获取用户名。在验证它之后,我尝试将自定义响应从此类发送回使用此api/rest auth/login/的消费者,因为CustomAuthentication类将在调用api/rest auth/login/时执行。希望你知道我在尝试什么,如果不让我知道的话,朋友。嗨,阿尔菲,我更新了我的代码。请看一下。@Teja谢谢,让我试试这个。我将在这里更新它是否对我有效。Hii Teja,我更新了我的代码。请调查一下。嗨,苏尼尔,我已经根据你的问题代码更新了我的答案。希望有帮助!