如何在 DRF 的 APIClient() delete() 请求中设置 headers?
How to set headers in DRF's APIClient() delete() request?
运行 测试时,我想创建然后删除一些资源。访问目标服务器需要使用令牌进行身份验证。
from django.test import TestCase
from rest_framework.test import APIClient
(...)
class MyTest(TestCase):
def setUp(self):
self.client = APIClient()
def test_creation_and_deletion(self):
payload = {"key": "value"}
# This works, but it's handled by a custom create() method from views.py:
res = self.client.post(<url>, payload)
(...)
# This doesn't work, no custom delete() method is defined anywhere:
tar_headers = {"private-token": "<token>"}
res2 = self.client.delete(res.data["target_resource_url"], headers=tar_headers)
# Either this doesn't work:
self.client.headers.update(tar_headers)
res3 = self.client.delete(res.data["target_resource_url"])
打印 res2
给出以下输出:
<HttpResponseNotFound status_code=404, "text/html">
调用res3
报错:
AttributeError: 'APIClient' object has no attribute 'headers'
从例如 target_resource_url
发送的删除请求只要在 headers.
中给出令牌,邮递员就可以正常工作
如何解决这个问题?
显然,在通过 APIClient()
请求删除时无法使用 Private-Token
进行身份验证。但是,可以使用旧的 requests
库:
import requests
HEADERS = {'PRIVATE-TOKEN': <TOKEN>}
res = ...
if "api_link" in res.data:
requests.delete(res.data["api_link"], headers=HEADERS)
运行 测试时,我想创建然后删除一些资源。访问目标服务器需要使用令牌进行身份验证。
from django.test import TestCase
from rest_framework.test import APIClient
(...)
class MyTest(TestCase):
def setUp(self):
self.client = APIClient()
def test_creation_and_deletion(self):
payload = {"key": "value"}
# This works, but it's handled by a custom create() method from views.py:
res = self.client.post(<url>, payload)
(...)
# This doesn't work, no custom delete() method is defined anywhere:
tar_headers = {"private-token": "<token>"}
res2 = self.client.delete(res.data["target_resource_url"], headers=tar_headers)
# Either this doesn't work:
self.client.headers.update(tar_headers)
res3 = self.client.delete(res.data["target_resource_url"])
打印 res2
给出以下输出:
<HttpResponseNotFound status_code=404, "text/html">
调用res3
报错:
AttributeError: 'APIClient' object has no attribute 'headers'
从例如 target_resource_url
发送的删除请求只要在 headers.
如何解决这个问题?
显然,在通过 APIClient()
请求删除时无法使用 Private-Token
进行身份验证。但是,可以使用旧的 requests
库:
import requests
HEADERS = {'PRIVATE-TOKEN': <TOKEN>}
res = ...
if "api_link" in res.data:
requests.delete(res.data["api_link"], headers=HEADERS)