Skip to content

Commit d21617f

Browse files
committed
Merge pull request #2519 from Ofir-Purple/optimize-token-auth-queries
Prefetching the user object when getting the token in TokenAuthentication
2 parents 4618134 + 58e7bbc commit d21617f

File tree

2 files changed

+7
-1
lines changed

2 files changed

+7
-1
lines changed

rest_framework/authentication.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,7 @@ def authenticate(self, request):
167167

168168
def authenticate_credentials(self, key):
169169
try:
170-
token = self.model.objects.get(key=key)
170+
token = self.model.objects.select_related('user').get(key=key)
171171
except self.model.DoesNotExist:
172172
raise exceptions.AuthenticationFailed('Invalid token')
173173

tests/test_authentication.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,12 @@ def test_post_json_passing_token_auth(self):
202202
response = self.csrf_client.post('/token/', {'example': 'example'}, format='json', HTTP_AUTHORIZATION=auth)
203203
self.assertEqual(response.status_code, status.HTTP_200_OK)
204204

205+
def test_post_json_makes_one_db_query(self):
206+
"""Ensure that authenticating a user using a token performs only one DB query"""
207+
auth = "Token " + self.key
208+
func_to_test = lambda: self.csrf_client.post('/token/', {'example': 'example'}, format='json', HTTP_AUTHORIZATION=auth)
209+
self.assertNumQueries(1, func_to_test)
210+
205211
def test_post_form_failing_token_auth(self):
206212
"""Ensure POSTing form over token auth without correct credentials fails"""
207213
response = self.csrf_client.post('/token/', {'example': 'example'})

0 commit comments

Comments
 (0)