本文介绍了“WSGIRequest'对象有没有属性'successful_authenticator”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个验证类就像这样:

I've made an authentication class just like that :

Token身份验证的RESTful API:应令牌定期更换

RESTAPI / settings.py

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        # 'rest_framework.authentication.TokenAuthentication',
        'restapi.authentication.ExpiringTokenAuthentication',
    ),
    'PAGINATE_BY': 10
}

RESTAPI / authentication.py

import datetime
from rest_framework.authentication import TokenAuthentication

class ExpiringTokenAuthentication(TokenAuthentication):
    def authenticate_credentials(self, key):
        try:
            token = self.model.objects.get(key=key)
        except self.model.DoesNotExist:
            raise exceptions.AuthenticationFailed('Invalid token')

        if not token.user.is_active:
            raise exceptions.AuthenticationFailed('User inactive or deleted')

        # This is required for the time comparison
        utc_now = datetime.utcnow()
        utc_now = utc_now.replace(tzinfo=pytz.utc)

        if token.created < utc_now - timedelta(hours=24):
            raise exceptions.AuthenticationFailed('Token has expired')

        return token.user, token

RESTAPI / tests.py

def test_get_missions(self):
    """
    Tests that /missions/ returns with no error
    """
    response = self.client.get('/missions/', HTTP_AUTHORIZATION = self.auth)

在我的测试中,我有一个例外, AttributeError的:WSGIRequest'对象有没有属性'successful_authenticator

In my tests, I have an exception AttributeError: 'WSGIRequest' object has no attribute 'successful_authenticator'

为什么我这个错误?如何解决呢?

Why am I having this error? How to fix it?

推荐答案

这个问题来自行:

utc_now = datetime.utcnow()

这将导致 AttributeError的:WSGIRequest'对象有没有属性'successful_authenticator

这是一段时间,因为我已经在这种误导性的错误消息绊倒了。

It's been a while since I've stumbled upon such a misleading error message.

下面是我如何解决它:

RESTAPI / authentication.py

import datetime
from django.utils.timezone import utc
from rest_framework.authentication import TokenAuthentication
from rest_framework import exceptions

class ExpiringTokenAuthentication(TokenAuthentication):
    def authenticate_credentials(self, key):
        try:
            token = self.model.objects.get(key=key)
        except self.model.DoesNotExist:
            raise exceptions.AuthenticationFailed('Invalid token')

        if not token.user.is_active:
            raise exceptions.AuthenticationFailed('User inactive or deleted')

        utc_now = datetime.datetime.utcnow().replace(tzinfo=utc)

        if token.created < utc_now - datetime.timedelta(hours=24):
            raise exceptions.AuthenticationFailed('Token has expired')

        return (token.user, token)

这篇关于“WSGIRequest'对象有没有属性'successful_authenticator”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 00:22