如何使用rest发送多个文件_framework.test.APITestCas

2024-06-08 01:12:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将两个文件发送到后端:

class AccountsImporterTestCase(APITestCase):

    def test(self):
        data = [open('accounts/importer/accounts.csv'), open('accounts/importer/apartments.csv')]
        response = self.client.post('/api/v1/accounts/import/', data, format='multipart')
        self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)

但我得到一个错误:

^{pr2}$

我知道我没有正确地准备数据,但有可能吗?,怎么了?。谢谢!在

更新:尝试@Kevin Brown解决方案

def test(self):
    data = QueryDict('', mutable=True)
    data.setlist('files', [open('accounts/importer/accounts.csv'), open('accounts/importer/apartments.csv')])
    response = self.client.post('/api/v1/accounts/import/', data, format='multipart')
    self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)

得到以下信息:

Error
Traceback (most recent call last):
  File "/vagrant/conjuntos/accounts/tests/cases.py", line 130, in test
    response = self.client.post('/api/v1/accounts/import/', data, format='multipart')
  File "/vagrant/venv/lib/python3.4/site-packages/rest_framework/test.py", line 168, in post
    path, data=data, format=format, content_type=content_type, **extra)
  File "/vagrant/venv/lib/python3.4/site-packages/rest_framework/test.py", line 89, in post
    data, content_type = self._encode_data(data, format, content_type)
  File "/vagrant/venv/lib/python3.4/site-packages/rest_framework/test.py", line 64, in _encode_data
    ret = renderer.render(data)
  File "/vagrant/venv/lib/python3.4/site-packages/rest_framework/renderers.py", line 757, in render
    return encode_multipart(self.BOUNDARY, data)
  File "/vagrant/venv/lib/python3.4/site-packages/django/test/client.py", line 182, in encode_multipart
    return b'\r\n'.join(lines)
TypeError: sequence item 4: expected bytes, bytearray, or an object with the buffer interface, str found

Tags: inpytestselfformatdatavenvresponse
2条回答

检查这是否解决了您的问题,因为它清楚地表明数据不应是列表

data = {"account_csv": open('accounts/importer/accounts.csv'), "apartments_csv": open('accounts/importer/apartments.csv')}

您可能会发现这个链接很有用Uploading multiple files in a single request using python requests module

您正在将文件列表发送到视图,但没有正确发送它们。当您向视图发送数据时,不管它是Django视图还是DRF视图,都应该将其作为键值对的列表发送。在

{
  "key": "value",
  "file": open("/path/to/file", "rb"),
}

回答你的问题。。。在

is it possible to do it?

似乎不可能使用同一个键上载多个文件(在测试中),但可以将它们分散到多个键上以实现相同的目标。或者,您可以将视图设置为只处理单个文件,并有多个测试覆盖不同的测试用例(apartments.csvaccounts.csv,等等)。在

由于传递的是单个列表而不是字典,Django无法正确解析它们,因此触发了异常。在

通过直接形成请求字典using a ^{},这是Django使用的表单数据的内部表示形式,您可能会有一些运气。在

^{pr2}$

因为这将更接近于通过浏览器发送的数据。这还没有经过测试,但它是在一个键中发送多个非文件值的方法。在

相关问题 更多 >

    热门问题