在DRF测试APIClient中添加自定义标头

huangapple go评论51阅读模式
英文:

Adding custom header to DRF test APIClient

问题

我需要为测试向APIClient添加自定义标头。
我已经尝试按照官方文档的这一部分进行操作(https://www.django-rest-framework.org/api-guide/testing/#credentialskwargs)

from rest_framework.test import APIClient
client = APIClient()
client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)

按照官方文档的步骤会导致错误,因为标头名称包含连字符。
这会引发语法错误,因为名称无效。

from rest_framework.test import APIClient
client = APIClient()
client.credentials(HEADER-WITH-HYPHEN='Token ' + token.key)

我还尝试使用from rest_framework.test import RequestsClient,但这需要URL包含http,而在测试时这是不可能的,因为服务器没有运行。

也不可能将标头名称更改为更符合Python规范的内容 在DRF测试APIClient中添加自定义标头

英文:

I need to add a custom header to the APIClient for a test.
I have tried to follow this section of the official docs

from rest_framework.test import APIClient
client = APIClient()
client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)

Following the official docs results in an error because the name has hyphens
This raises a syntax error because the name is not valid.

from rest_framework.test import APIClient
client = APIClient()
client.credentials(HEADER-WITH-HYPHEN='Token ' + token.key)

I also tried using from rest_framework.test import RequestsClient but this needs the url to include http which isn't possible because the server doesn't run while testing.

It also isn't possible to change the header name to something more pythonic 在DRF测试APIClient中添加自定义标头

答案1

得分: 1

显然,这个 client.credentials(HTTP_header_with_hyphen=token) 将会在请求头中评估为 {"Header-With-Hyphen": token}

英文:

Apparently, this client.credentials(HTTP_header_with_hyphen=token) will evaluate to {"Header-With-Hyphen": token} in the request header.

huangapple
  • 本文由 发表于 2023年5月29日 03:43:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76353319.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定