gpt4 book ai didi

python - Django Rest Framework - 将带有文件和其他数据的多部分/表单数据发送到 API

转载 作者:行者123 更新时间:2023-12-05 04:05:07 26 4
gpt4 key购买 nike

我正在尝试为我的网络应用程序创建一些自动化测试,它使用 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')]}

未检测到内容已发送,关于如何修复它的任何想法,或完成相同事情的更好方法?

最佳答案

通过更仔细地阅读文档解决了这个问题,如果没有内容类型传递给 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)

关于python - Django Rest Framework - 将带有文件和其他数据的多部分/表单数据发送到 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51574998/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com