python - Django REST框架: error when testing POST request with list

标签 python django django-rest-framework

我有一个测试 View :

@api_view(['POST'])
@permission_classes([AllowAny])
@authentication_classes([])
def test_view(request):
    return Response(request.data)

它在urls.py中注册:

urlpatterns = [
    path('api/test/', test_view)
]

当我尝试通过 REST Frameworks UI 手动 POST [{"a": 1}, {"a": 2}] 时,一切正常。

但是,如果我为其编写测试,则会发生意外错误。这是测试

from rest_framework.test import APITestCase

class ViewTest(APITestCase):
    def test_it(self):
        response = self.client.post('/api/test/', [{"a": 1}, {"a": 2}])
        print(response)

这会产生以下错误:

Traceback (most recent call last):
  File "C:\development\HeedView\backend\clients\api\tests.py", line 13, in test_it
    response = self.client.post('/api/test/', [{"a":1}, {"a": 2}])
  File "C:\development\HeedView\venv\lib\site-packages\rest_framework\test.py", line 300, in post
    path, data=data, format=format, content_type=content_type, **extra)
  File "C:\development\HeedView\venv\lib\site-packages\rest_framework\test.py", line 212, in post
    data, content_type = self._encode_data(data, format, content_type)
  File "C:\development\HeedView\venv\lib\site-packages\rest_framework\test.py", line 184, in _encode_data
    ret = renderer.render(data)
  File "C:\development\HeedView\venv\lib\site-packages\rest_framework\renderers.py", line 921, in render
    return encode_multipart(self.BOUNDARY, data)
  File "C:\development\HeedView\venv\lib\site-packages\django\test\client.py", line 194, in encode_multipart
    for (key, value) in data.items():
AttributeError: 'list' object has no attribute 'items'

如何解释这种行为?

最佳答案

要传递json数据,需要添加format='json'。此测试有效:

from rest_framework.test import APITestCase

class ViewTest(APITestCase):
    def test_it(self):
        response = self.client.post('/api/test/', [{"a": "1"}, {"a": 2}], format='json')
        print(response.json())

或者,如果您set the default format,则您的原始测试有效。在settings.py中:

REST_FRAMEWORK = {
    ...
    'TEST_REQUEST_DEFAULT_FORMAT': 'json'
}

如果未指定格式:

Rest Framework APIClient扩展 Django 现有的 Client 类。 documentation for Client.post解释说:

The key-value pairs in the data dictionary are used to submit POST data. For example:

... client.post('/login/', {'name': 'fred', 'passwd': 'secret'})

... [tests] this POST data:

name=fred&passwd=secret

您的原始测试返回错误,因为如果未指定格式,则 Django 需要字典,而不是列表。

关于python - Django REST框架: error when testing POST request with list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58252536/

相关文章:

python - ttk.Entry.select_range() 适用于 Button,但不适用于 python/tkinter 中的 ttk.Button?

python - Django、uwsgi、nginx、virtualenv、ImportError : No module named site

django - 在 Django 中使用 trigram 进行文本搜索

python - 使用 django-rest-framework 设置对象级权限

python - 将自定义响应 header 添加到 APIException

python - Django REST 将空替换为默认值

python - 相同元素的排列 : efficiently avoid redundant permutations

子类化 OpenerDirector 的 Pythonic 方式

Python 测试 url 和图像类型

python - POST 保存后更新模型中的字段之一