django - 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
不为空,所以我猜测试有问题。
解决方案
这应该工作
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)
推荐阅读
- python - ValueError:输入包含的值对于 dtype('float32') 来说太大了
- javascript - vue - 如何在 Slick-carousel 中的弹性项目之间制作间隙
- php - sendinblue php,如何添加附件
- c - 给定的代码在函数调用中如何工作?
- react-native - React 原生声音使用户音乐静音(Spotify、deezer 等)
- windows - 我如何从另一台电脑连接到我的本地主机服务器?(在同一个网络)
- laravel - 在 laravel 中配置电子邮件传递?
- google-chrome - 在 Chrome Devtools Inspector 中禁用“长度创作工具”(css 单位选择器)
- laravel - Laravel 获取所有未触发时间戳 19 天的记录
- html - Bootsrap 4 登录页面添加左侧卡片和右侧重叠图像问题