首页 > 解决方案 > django rest:测试文件上传但 request.data 为空

问题描述

我尝试使用 django rest 框架测试文件上传,但它request.data是空的

测试:

def test_update_story_cover(self):
    auth_token, story_id = self.create_story()
    image_path = os.path.join(os.path.dirname(__file__), 'book.jpg')
    url = reverse('story_modify', kwargs={'pk': story_id})

    with open(image_path) as cover:
        response = self.client.patch(
            url, data={'cover': cover, 'title': 'test title'},
            content_type='multipart/form-data',
            HTTP_AUTHORIZATION=auth_token)

    self.assertEqual(response.status_code, status.HTTP_200_OK)

看法:

class StoryModifyView(RetrieveUpdateDestroyAPIView):
    ...

    def update(self, request, *args, **kwargs):
        print(request.data)
        print(request.FILES)
        print(request.body)
        ...

输出是

<QueryDict: {}> {}
<MultiValueDict: {}>
b"{'cover': <_io.TextIOWrapper name='/some-path/stories/tests/test_stories/books.jpg' mode='r' encoding='UTF-8'>, 'title': 'test title'}"

真正的前端可以成功上传图片,并且request.data不为空,所以我猜测试有问题。

标签: djangodjango-rest-framework

解决方案


这应该工作

from rest_framework.test import APIClient

def test_update_story_cover(self):
    client = APIClient()        

    auth_token, story_id = self.create_story()
    image_path = os.path.join(os.path.dirname(__file__), 'book.jpg')
    url = reverse('story_modify', kwargs={'pk': story_id})

    with open(image_path, 'rb') as cover:
        response = client.patch(
            path=url, data={'cover': cover, 'title': 'test title'},
            format='multipart',
            HTTP_AUTHORIZATION=auth_token)

    self.assertEqual(response.status_code, status.HTTP_200_OK)

推荐阅读