drf 自带token学习记录

核心代码
获取token接口,传递用户密码


url(r'^api-token-auth/',obtain_auth_token),

class ObtainAuthToken(APIView):
。。。。
  serializer_class = AuthTokenSerializer

def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data,
context={'request': request})
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
token, created = Token.objects.get_or_create(user=user)
return Response({'token': token.key})





验证用户密码模块

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

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

if username and password:
user = authenticate(request=self.context.get('request'),
username=username, password=password)

# The authenticate call simply returns None for is_active=False
# users. (Assuming the default ModelBackend authentication
# backend.)
if not user:
msg = _('Unable to log in with provided credentials.')
raise serializers.ValidationError(msg, code='authorization')
else:
msg = _('Must include "username" and "password".')
raise serializers.ValidationError(msg, code='authorization')

attrs['user'] = user
return attrs



上一篇:自定义View 水波纹


下一篇:Java获取服务器系统默认编码格式