gpt4 book ai didi

django - 'WSGIRequest' 对象没有属性 'successful_authenticator'

转载 作者:行者123 更新时间:2023-12-04 14:14:31 27 4
gpt4 key购买 nike

我已经制作了一个这样的身份验证类:

Token Authentication for RESTful API: should the token be periodically changed?
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' object has no attribute 'successful_authenticator'
为什么我有这个错误?如何解决?

最佳答案

问题来自这一行:

utc_now = datetime.utcnow()

这导致 AttributeError: 'WSGIRequest' object has no attribute 'successful_authenticator' .

自从我偶然发现这种误导性的错误消息以来,已经有一段时间了。

这是我解决它的方法:
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)

关于django - 'WSGIRequest' 对象没有属性 'successful_authenticator',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16736710/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com