mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-22 17:47:04 +03:00
Prefetching the user object when getting the token in TokenAuthentication.
Since the user object is fetched 4 lines after getting Token from the database, this removes a DB query for each token-authenticated request.
This commit is contained in:
parent
46181341d5
commit
58e7bbc8ec
|
@ -167,7 +167,7 @@ class TokenAuthentication(BaseAuthentication):
|
|||
|
||||
def authenticate_credentials(self, key):
|
||||
try:
|
||||
token = self.model.objects.get(key=key)
|
||||
token = self.model.objects.select_related('user').get(key=key)
|
||||
except self.model.DoesNotExist:
|
||||
raise exceptions.AuthenticationFailed('Invalid token')
|
||||
|
||||
|
|
|
@ -202,6 +202,12 @@ class TokenAuthTests(TestCase):
|
|||
response = self.csrf_client.post('/token/', {'example': 'example'}, format='json', HTTP_AUTHORIZATION=auth)
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
|
||||
def test_post_json_makes_one_db_query(self):
|
||||
"""Ensure that authenticating a user using a token performs only one DB query"""
|
||||
auth = "Token " + self.key
|
||||
func_to_test = lambda: self.csrf_client.post('/token/', {'example': 'example'}, format='json', HTTP_AUTHORIZATION=auth)
|
||||
self.assertNumQueries(1, func_to_test)
|
||||
|
||||
def test_post_form_failing_token_auth(self):
|
||||
"""Ensure POSTing form over token auth without correct credentials fails"""
|
||||
response = self.csrf_client.post('/token/', {'example': 'example'})
|
||||
|
|
Loading…
Reference in New Issue
Block a user