英文:
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规范的内容
英文:
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
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论