让用户忘记
令牌认证功能将令牌分配给用户,因此每次使用该令牌时,请求对象都将具有保存用户模型信息的用户属性。容易,不是吗?
只要请求包含正确的用户和密码,我们将创建一个新的 POST 方法来返回此用户的令牌。打开位于 test_app 应用程序文件夹中的 views.py .
from rest_framework.response import Response
from rest_framework.authtoken.models import Token
from rest_framework.exceptions import ParseError
from rest_framework import status
from django.contrib.auth.models import User
# Create your views here.
class TestView(APIView):
"""
"""
def get(self, request, format=None):
return Response({'detail': "GET Response"})
def post(self, request, format=None):
try:
data = request.DATA
except ParseError as error:
return Response(
'Invalid JSON - {0}'.format(error.detail),
status=status.HTTP_400_BAD_REQUEST
)
if "user" not in data or "password" not in data:
return Response(
'Wrong credentials',
status=status.HTTP_401_UNAUTHORIZED
)
user = User.objects.first()
if not user:
return Response(
'No default user, please create one',
status=status.HTTP_404_NOT_FOUND
)
token = Token.objects.get_or_create(user=user)
return Response({'detail': 'POST answer', 'token': token[0].key})