我正在使用 django rest_framework 并使用一个 API,该 API 会带来标头值来验证发送者。当我使用 APIClient 测试我制作的 webhook 时遇到问题。
@pytest.mark.django_db
def test_change_status_webhook_ok(webhook_client, status_changes):
fixture_signature = (
"51b93156c361bfce14c527ddcb27cc3791e9ea6ede23bc5a56efa3be28e6a54d"
)
url = reverse("webhook_v1:notification")
response = webhook_client.post(
url,
json.dumps(status_changes),
content_type="application/json",
**{"X-Extserv-Signature": fixture_signature}
)
assert response.status_code == 200
问题是当我尝试从标头获取 X-Extserv-Signature 时。 我尝试过:
ret = request.headers.get("X-Extserv-Signature")
这种方式仅在我收到来自邮递员的请求时才有效。但是当我从 APIClient 发出请求并且无法使用上面相同的代码获取值时,下面的表单才有效。
ret = request.META["X-Extserv-Signature"]
您知道如何将
X-Extserv-Signature
键值设置为 APIClient 中的标头吗?
docs
:
一个不区分大小写、类似字典的对象,提供对所有 HTTP 前缀标头的访问
request.headers
将仅包含 HTTP 前缀的标头,因此:
response = webhook_client.post(
url,
json.dumps(status_changes),
content_type="application/json",
**{"HTTP_X_EXTSERV_SIGNATURE": fixture_signature} # <-- Use this
)
选项:
**{"HTTP_X_EXTSERV_SIGNATURE": fixture_signature} # <-- Use this
它对我不起作用,但这个却有用:
client = api_client()
resp = client.post(
'/iip/api/v0/handler',
request_body,
format='json',
HTTP_X_EXTSERV_SIGNATURE=token,
)