don't import authtoken model until needed

This commit is contained in:
S. Andrew Sheppard 2015-12-30 15:44:19 -06:00
parent af0ea8ef51
commit ff29fdd875
2 changed files with 9 additions and 11 deletions

View File

@ -10,7 +10,6 @@ from django.middleware.csrf import CsrfViewMiddleware
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from rest_framework import HTTP_HEADER_ENCODING, exceptions from rest_framework import HTTP_HEADER_ENCODING, exceptions
from rest_framework.authtoken.models import Token
def get_authorization_header(request): def get_authorization_header(request):
@ -149,7 +148,14 @@ class TokenAuthentication(BaseAuthentication):
Authorization: Token 401f7ac837da42b97f613d789819ff93537bee6a Authorization: Token 401f7ac837da42b97f613d789819ff93537bee6a
""" """
model = Token model = None
def get_model(self):
if self.model is not None:
return self.model
from rest_framework.authtoken.models import Token
return Token
""" """
A custom token model may be used, but must have the following properties. A custom token model may be used, but must have the following properties.
@ -180,7 +186,7 @@ class TokenAuthentication(BaseAuthentication):
def authenticate_credentials(self, key): def authenticate_credentials(self, key):
try: try:
token = self.model.objects.select_related('user').get(key=key) token = self.get_model().objects.select_related('user').get(key=key)
except self.model.DoesNotExist: except self.model.DoesNotExist:
raise exceptions.AuthenticationFailed(_('Invalid token.')) raise exceptions.AuthenticationFailed(_('Invalid token.'))

View File

@ -21,14 +21,6 @@ class Token(models.Model):
user = models.OneToOneField(AUTH_USER_MODEL, related_name='auth_token') user = models.OneToOneField(AUTH_USER_MODEL, related_name='auth_token')
created = models.DateTimeField(auto_now_add=True) created = models.DateTimeField(auto_now_add=True)
class Meta:
# Work around for a bug in Django:
# https://code.djangoproject.com/ticket/19422
#
# Also see corresponding ticket:
# https://github.com/tomchristie/django-rest-framework/issues/705
abstract = 'rest_framework.authtoken' not in settings.INSTALLED_APPS
def save(self, *args, **kwargs): def save(self, *args, **kwargs):
if not self.key: if not self.key:
self.key = self.generate_key() self.key = self.generate_key()