APIClient的PUT调用中的查询参数



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

我在文档中读到,对于 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构建真的有必要吗?

假设你使用的是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)

而 put 是:

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创建那个字典,并将其传递给put的kwargs,我不确定这在努力方面有多值得。

我只是指定@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'))

最新更新