Django 2.1令牌匹配查询不存在

时间:2019-04-07 07:10:36

标签: python django authentication django-rest-framework jwt

我一直在尝试使用this guide中的rest_framework.authtoken在Django中实现用户认证。我的测试用例测试了用户登录时可能出现的各种不同的错误,在将访问令牌引入代码之前,它们可以正常工作。

由于某种原因,当我添加对Http响应中返回的令牌的检查时,出现错误:

rest_framework.authtoken.models.Token.DoesNotExist: Token matching query does not exist.

我已经添加了检查令牌所需的所有相关导入,因此是否可以将某个函数在新的Django版本之一中重定位到其他库?可能是什么原因引起的?

test.py

from django.urls import reverse 
from rest_framework.test import APITestCase
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.authtoken.models import Token


class AccountsTest(APITestCase):
    def setUp(self):
        # We want to go ahead and originally create a user. 
        self.test_user = User.objects.create_user('testuser', 'test@example.com', 'testpassword')
        print('test user:' + str(self.test_user))

        # URL for creating an account.
        self.create_url = reverse('account-create')

    def test_create_user(self):
        """
        Ensure we can create a new user and a valid token is created with it.
        """
        data = {
                'username': 'foobar',
                'email': 'foobar@example.com',
                'password': 'somepassword'
                }

        response = self.client.post(self.create_url , data, format='json')
        user = User.objects.latest('id')

        token = Token.objects.get(user=user)
        self.assertEqual(response.data['token'], token.key)

views.py

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from accounts.serializers import UserSerializer
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token

class UserCreate(APIView):
    """ 
    Creates the user. 
    """

    def post(self, request, format='json'):
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            user = serializer.save()
            if user:
                token = Token.objects.create(user=user)
                json = serializer.data
                json['token'] = token.key
                return Response(json, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    #third party
    'rest_framework',
    'rest_framework.authtoken',

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.TokenAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
    'rest_framework.permissions.IsAuthenticatedOrReadOnly',
    ),
}

2 个答案:

答案 0 :(得分:0)

由于您的设置文件具有以下权限类别,因此它将适用于扩展了APIView的所有视图

'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticatedOrReadOnly', )

因此,请设置default config as same。通过在permission_classes中设置APIView属性来覆盖它,如下所示。

from rest_framework.permissions import AllowAny
class UserCreate(APIView):
     permission_classes = (AllowAny,)

答案 1 :(得分:0)

就我而言,我能够使用 .get_or_create 而不是仅使用 .get 来传递错误。