【问题标题】:Django Rest Framework - Send multipart/form-data with file and other data to APIDjango Rest Framework - 将带有文件和其他数据的 multipart/form-data 发送到 API
【发布时间】:2019-01-05 14:01:38
【问题描述】:

我正在尝试为我的网络应用程序创建一些自动化测试,该应用程序使用 Django 和 DRF 作为后端来处理来自前端的请求。

我无法找到一种方法来使用客户端向 API 发送一些表单数据,我收到一个错误,即没有发布任何字段。

这是我使用 APITestCase 类的尝试:

from django.test import TestCase, TransactionTestCase
from django.core.exceptions import ObjectDoesNotExist
from django.urls import reverse

from rest_framework.test import APIRequestFactory, APITestCase, APIClient, RequestsClient, APITransactionTestCase

import json, os, re
import requests as python_requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
....
....
def testInvoiceUploadAndRead(self):
        #test non-logged in user
        response=self.client.get(reverse("invoiceupload"))
        self.assertEqual(response.status_code, 403)

        user=Account.objects.get(username="test_user")
        self.client.login(username=user.username, password="rebar123")
        response=self.client.get(reverse("invoiceupload"))
        self.assertEqual(response.status_code, 405)
        #create the invoice
        full_filename=os.path.join("media", "testfiles", "sample_file.png")
        invoice = MultipartEncoder(
            fields={
                "invoicefile":("test_file.png", open(full_filename, "rb")),
                "debtor":"5560360793",
                "amount":"55000",
                "serial":"1234567890",
                "dateout":"20180728",
                "expiration":"20180808",
            }
        )
        response=self.client.post(reverse("invoiceupload"), invoice, content_type="multipart/form-data")
        print(response.data["message"])
        self.assertEqual(response.status_code, 201)

我收到了错误:

{'debtor': [ErrorDetail(string='This field is required.', code='required')], 'invoicefile': [ErrorDetail(string='No file was submitted.', code='required')], 'expiration': [ErrorDetail(string='This field is required.', code='required')], 'dateout': [ErrorDetail(string='This field is required.', code='required')], 'amount': [ErrorDetail(string='This field is required.', code='required')], 'serial': [ErrorDetail(string='This field is required.', code='required')]}

没有检测到发送的内容,有什么关于如何修复它的想法,或者更好的方法来完成同样的事情?

【问题讨论】:

  • 有什么更新吗?

标签: python django file-upload django-rest-framework python-requests


【解决方案1】:

通过更仔细地阅读文档解决了这个问题,如果没有将内容类型传递给 post 方法,它会自动设置我的观点接受的 multipart/form-data。

变化:

invoice = {
    "invoicefile":(open(full_filename, "rb")),
    "debtor":"5560360793",
    "amount":"55000",
    "serial":"1234567890",
    "dateout":"20180728",
    "expiration":"20180808",
}
response = self.client.post(reverse("invoiceupload"), invoice)
self.assertEqual(response.status_code, 201)

【讨论】:

    猜你喜欢
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-22
    • 2016-06-13
    • 1970-01-01
    • 2021-04-30
    • 2012-10-01
    相关资源
    最近更新 更多