在TEST模式DRF中将标记添加到标头请求

时间:2017-11-16 14:08:00

标签: django-rest-framework testcase django-tests

如何在Django / DRF中向TEST请求添加'Authorization': 'Token'

如果我使用简单的requests.get(url, headers={'Authorization': 'Token'}所有工作都很完美,但如何在TestCase中执行此类请求?

1 个答案:

答案 0 :(得分:8)

参考:http://www.django-rest-framework.org/api-guide/testing/#credentialskwargs

from rest_framework.authtoken.models import Token
from rest_framework.test import APIClient

# Include an appropriate `Authorization:` header on all requests.
token = Token.objects.get(user__username='lauren')
client = APIClient()
client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)