【问题标题】:Django testing post request with multipart/form data and a dictionaryDjango 使用多部分/表单数据和字典测试发布请求
【发布时间】:2021-05-02 12:46:51
【问题描述】:

我的客户端使用 requests 库来调用我的 Django 服务器

import requests
response = requests.post(url, files=dict({
            'value': 'key',
        }))

这将创建一个请求,将字典作为<MultiValueDict: {}> 插入字段request.FILES

我正在尝试使用 django.test 重新创建它。
我一直想尝试类似的东西

from django.test import TestCase, Client
client = Client()
response = client.post('/sign', dict(request_data))

但是request.FILES 对象是空的

编辑---- 我也试过同样的结果(request.FILES -> <MultiValueDict: {}>

client.post('/sign', {'file': dict({
  'key' : 'value'
})})

编辑 2---

查看我正在检查值的中间件


class ApiAuthenticationMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request: HttpRequest):
        print(request.FILES)
        

【问题讨论】:

  • 不,我也试过了。当你这样做时,request.FILES 处的字典仍然是空的
  • 用 request_data 更新了帖子
  • 相同结果 - client.post('/sign', **{'file': dict({'key': 'value'})})
  • 在编辑中添加了更多上下文
  • 这包含许多答案。阅读所有这些可能会有所帮助。 stackoverflow.com/questions/11170425/…

标签: python django integration-testing multipartform-data


【解决方案1】:

解决方案

        fake_file.name = 'data.json'
        post_data = {
            'data.json': fake_file,
        }
        return self.client.post('/sign', post_data,  content_type=MULTIPART_CONTENT)

【讨论】:

    猜你喜欢
    • 2016-11-11
    • 2020-01-18
    • 1970-01-01
    • 2020-03-14
    • 2022-11-15
    • 2018-03-19
    • 2019-03-02
    • 1970-01-01
    • 2017-07-29
    相关资源
    最近更新 更多