[英]Django DRF Post with files and data works in Postman, not Python. No TemporaryUploadedFile
在本地運行 Django 應用程序,我可以使用 Postman 上傳 zip 文件以及一些 dict 數據。 在'def Post()'中破壞應用程序我可以看到郵遞員成功上傳:
request.data = <QueryDict: {'request_id': ['44'], 'status': [' Ready For Review'], 'is_analyzed': ['True'], 'project': ['test value'], 'plate': ['Plate_R0'], 'antigen': ['tuna'], 'experiment_type': ['test'], 'raw_file': [<TemporaryUploadedFile: testfile.zip (application/zip)>]}>
Postman 提供以下 python 代碼以在我的 python 腳本中復制這些結果:
import requests
url = "http://127.0.0.1:8000/api/upload/"
payload = {'request_id': '44',
'status': ' Ready For Review',
'is_analyzed': 'True',
'project': 'test value',
'plate': 'Plate_R0',
'antigen': 'tuna',
'experiment_type': 'test'}
files = [
('raw_file', open(r'C:/testfile.zip','rb'))
]
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
response = requests.request("POST", url, headers=headers, data = payload, files = files)
print(response.text.encode('utf8'))
直接運行此代碼並檢索 request.data(服務器端)我看到 xlsx 文件的二進制表示在 object 中,並且有效負載數據不存在(這是響應中的錯誤)。
如何讓我的 python 腳本生成與 postman 相同的服務器端 object? 具體來說,我如何上傳我的數據,使文件表示為:<TemporaryUploadedFile: testfile.zip (application/zip)>
謝謝。
事實證明,對 Postman 發布的 object 的檢查表明它正在使用多部分格式上傳。 環顧四周,我發現了一個相關問題的答案,將發布描述為多部分: https://stackoverflow.com/a/50595768/2917170 。
工作 python 如下:
from requests_toolbelt import MultipartEncoder
url = "http://127.0.0.1:8000/api/upload/"
zip_file = r'C:/testfile.zip'
m = MultipartEncoder([('raw_file', (os.path.basename(zip_file), open(zip_file, 'rb'))),
('request_id', '44'),
('status', 'Ready For Review'),
('is_analyzed', 'True'),
('project', 'test value'),
('plate', 'Plate_R0'),
('antigen', 'tuna'),
('experiment_type', 'test')])
header = {'content-type': m.content_type}
response = requests.post(url, headers=header, data=m, verify=True)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.