讓使用者忘記

令牌認證功能將令牌分配給使用者,因此每次使用該令牌時,請求物件都將具有儲存使用者模型資訊的使用者屬性。容易,不是嗎?

只要請求包含正確的使用者和密碼,我們將建立一個新的 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})