如何在Django / DRF中向TEST请求添加'Authorization': 'Token'
?
如果我使用简单的requests.get(url, headers={'Authorization': 'Token'}
所有工作都很完美,但如何在TestCase中执行此类请求?
答案 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)