【问题标题】:How to set headers in DRF's APIClient() delete() request?如何在 DRF 的 APIClient() delete() 请求中设置标头?
【发布时间】:2020-04-14 15:59:04
【问题描述】:

在运行测试时,我想创建然后删除一些资源。访问目标服务器需要使用令牌进行身份验证。

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 发送的删除请求只要在标头中给出令牌,邮递员就可以正常工作。

如何解决这个问题?

【问题讨论】:

  • 这对您有帮助吗? DRF headers & authentication
  • HTTPBasicAuth 需要用户名和密码,我认为它不接受任何其他值,因此无法在此处应用。
  • 这与 HTTPBasicAuth 无关,只是简单地添加 client.headers.update({'x-test': 'true'})
  • 报错,我只是在上面的标记中添加了res3,请看一下。

标签: django django-rest-framework django-unittest


【解决方案1】:

显然,在通过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)

【讨论】:

    猜你喜欢
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    • 2012-03-28
    • 2018-03-30
    • 2020-10-09
    • 1970-01-01
    • 2012-10-03
    • 1970-01-01
    相关资源
    最近更新 更多