APIClient PUT 调用中的查询参数

phy*_*ion 5 django django-testing apiclient

我有一个 API 端点,我想对其进行 PUT 调用,该调用需要正文和查询参数。我使用 Django 的测试客户端在测试用例(文档)中调用我的端点。

我在文档中读到,对于 GET 调用,查询参数是使用 argument 引入的data。我还读到,对于 PUT 调用,参数data代表主体。我错过了如何在 PUT 调用中添加查询参数的文档。

特别是,这个测试用例失败了:

data = ['image_1', 'image_2']
url = reverse('images')
response = self.client.put(url, 
                           data=data, 
                           content_type='application/json', 
                           params={'width': 100, 'height': 200})
Run Code Online (Sandbox Code Playgroud)

这个测试用例通过了:

data = ['image_1', 'image_2']
url = reverse('images') + '?width=100&height=200'
response = self.client.put(url, 
                           data=data, 
                           content_type='application/json')
Run Code Online (Sandbox Code Playgroud)

换句话说:这种手动 URL 构建真的有必要吗?

hen*_*aro 3

假设您正在使用 rest_framework's APITestClient,我发现了这一点:

def get(self, path, data=None, secure=False, **extra):
    """Construct a GET request."""
    data = {} if data is None else data
    r = {
        'QUERY_STRING': urlencode(data, doseq=True),
    }
    r.update(extra)
    return self.generic('GET', path, secure=secure, **r)
Run Code Online (Sandbox Code Playgroud)

而看跌期权是:

def put(self, path, data='', content_type='application/octet-stream',
        secure=False, **extra):
    """Construct a PUT request."""
    return self.generic('PUT', path, data, content_type,
                        secure=secure, **extra)
Run Code Online (Sandbox Code Playgroud)

以及有趣的部分(代码摘录self.generic):

    # If QUERY_STRING is absent or empty, we want to extract it from the URL.
    if not r.get('QUERY_STRING'):
        # WSGI requires latin-1 encoded strings. See get_path_info().
        query_string = force_bytes(parsed[4]).decode('iso-8859-1')
        r['QUERY_STRING'] = query_string
    return self.request(**r)
Run Code Online (Sandbox Code Playgroud)

所以你可能可以尝试创建该字典并将QUERY_STRING其传递给putkwargs,但我不确定这是否值得付出努力。