查询APIClient的PUT调用中的参数

问题描述 投票:2回答:2

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

我在文档中读到,对于GET调用,使用参数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})

这个测试用例通过:

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

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

django django-testing apiclient
2个回答
2
投票

假设你正在使用rest_framework的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)

而放置是:

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)

和有趣的部分(摘自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)

所以你可能会尝试用QUERY_STRING创建那个dict并将它传递给put的kwargs,但我不确定它是多么值得努力。


0
投票

我只是详细说明@henriquesalvaro的答案。

您可以在PUTPOST方法中传递查询参数,如下所示。

# tests.py
def test_xxxxx(self):
    url = 'xxxxx'
    res = self.client.put(url,**{'QUERY_STRING': 'a=10&b=20'})

# views.py
class TestViewSet(.....):

    def ...(self, request, *args, **kwargs):
        print(request.query_params.get('a'))
        print(request.query_params.get('b'))
© www.soinside.com 2019 - 2024. All rights reserved.