为什么django-rest-framework authenticate()签名与django authenticate()签名不同

时间:2016-03-25 15:48:57

标签: django django-rest-framework

我正在使用DRF为我的REST api实现正常的会话身份验证,并且无法使其正常工作,因为DRF身份验证后端具有authenticate()方法,其签名与普通Django'不同。秒。

以下是我的AuthViewLoginSerializer,它们大多是从DRF的自动包装中复制的:

views.py

from django.shortcuts import render
from django.template.response import TemplateResponse
from django.contrib.auth import login, logout
from django.http import Http404

from rest_framework import viewsets, views
from rest_framework import mixins
from rest_framework import response
from rest_framework import status
from rest_framework import authentication

from serializers import *
from models import *

class AuthView(views.APIView):
    authentication_classes = (authentication.SessionAuthentication, )
    serializer_class = LoginSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)

        if serializer.is_valid(raise_exception=True):
            user = serializer.validated_data['user']
            response_data = UserSerializer(user).data
            return response.Response(response_data)

        return response.Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

serializers.py

from django.contrib.auth import authenticate
from django.utils.translation import ugettext_lazy as _

from rest_framework import serializers
from rest_framework import relations

from models import *

class LoginSerializer(serializers.Serializer):
    username = serializers.CharField(label=_("Username"))
    password = serializers.CharField(label=_("Password"), style={'input_type': 'password'})

    def validate(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')

        if username and password:
            import pdb
            pdb.set_trace()
            user = authenticate(username=username, password=password)

            if user:
                if not user.is_active:
                    msg = _('User account is disabled.')
                    raise serializers.ValidationError(msg)
            else:
                msg = _('Unable to log in with provided credentials.')
                raise serializers.ValidationError(msg)
        else:
            msg = _('Must include "username" and "password".')
            raise serializers.ValidationError(msg)

        attrs['user'] = user
        return attrs

因此,LoginSerializer调用authenticate(username=username, password=password)作为普通的django身份验证函数。

它适用于普通的django django.contrib.auth.backends.ModelBackend,但是由于签名不兼容,DRF' rest_framework.authentication.SessionAuthentication会失败。

所有DRF的身份验证后端都希望authenticate()功能具有签名authenticate(self, request),这对我来说没有多大意义,因为请求不包含用户信息爱好。

我该怎么办?

0 个答案:

没有答案