python - 无法使用 DRF APIClient() 更改 header

标签 python django unit-testing django-rest-framework pytest

我使用 APIClient() 进行测试。 我使用 Token 认证,所以我需要使用 THIS

如果我们深入研究源代码,我们将看到接下来的内容:

# rest_framework/test.py
class APIClient(APIRequestFactory, DjangoClient):
    def __init__(self, enforce_csrf_checks=False, **defaults):
        super().__init__(**defaults)
        self.handler = ForceAuthClientHandler(enforce_csrf_checks)
        self._credentials = {}

    def credentials(self, **kwargs):
        """
        Sets headers that will be used on every outgoing request.
        """
        self._credentials = kwarg

我还在我的代码中使用 APIClient() 作为 pytest fixture:

@pytest.fixture(scope="function")
def _api():
    """API factory for anonymous and auth requests"""

    def __api(token=None, field=None):
        api_client = APIClient()
        headers = {}

        if token:
            headers["HTTP_AUTHORIZATION"] = f"Token {token}"
        if field:
            headers["X-CUSTOM-HEADER"] = field

        api_client.credentials(**headers)

        return api_client
    return __api

但是如果我们创建 TestMiddleware 来查找 header ,我们将看到下一个:

lass TestMiddleware:
    def __init__(self, get_response):
        self._get_response = get_response

    def __call__(self, request):
        header = request.headers.get("X-CUSTOM-HEADER") # None
        header = request.META.get("X-CUSTOM-HEADER") # Works fine!
        ...

        # Response processing
        response = self._get_response(request)

        return response

问题是我们有没有办法通过APIClient()访问X-CUSTOM-HEADER? 另外,如果我使用 Postman,它显然可以与 request.headers.get()

一起使用

最佳答案

kwargs 传递给了 credentials() method最终直接送入 constructor for a WSGIRequest ;这意味着它接受的 kwargs 不是 HTTP header ,而是 WSGI 环境变量。作为 WSGI 环境变量传递的 HTTP header 总是以 HTTP_ 为前缀——例如Authorization header 配置有 HTTP_AUTHORIZATION。此外,下划线用于代替破折号。

要让您的 X-Custom-Header header 出现在 request.headers 的另一侧(不是 request.META,它是WSGI 环境变量的副本),传递 HTTP_X_CUSTOM_HEADER 而不是 X-CUSTOM-HEADER

关于python - 无法使用 DRF APIClient() 更改 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66437820/

相关文章:

python - 使用 Django 在一页上登录和注册表格

django - ModelForm Django 1.11 覆盖错误消息

unit-testing - 相当于 "Package-Protected"用于 Typescript 测试?

javascript - 在 stub 函数之后它仍然调用真正的函数

unit-testing - hudson CI - 功能或单元测试用例?

python - 删除重复数据并将其余数据附加到 Pandas 中

python - Python语言会成为 future 最快的语言吗?

python - tensorflow 2.3 : AttributeError: 'Tensor' object has no attribute 'numpy'

python - 如何在 Django Photologue 中制作自定义照片效果?

python - 手动转义原始 SQL 的字符串