【问题标题】:Django DRF Post with files and data works in Postman, not Python. No TemporaryUploadedFile带有文件和数据的 Django DRF Post 在 Postman 中工作,而不是 Python。没有临时上传文件
【发布时间】:2020-11-20 16:41:47
【问题描述】:

在本地运行 Django 应用程序,我可以使用 Postman 上传 zip 文件以及一些 dict 数据。在 'def Post()' 中破坏应用程序,我可以看到 Postman 上传成功:

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 文件的二进制表示在对象中,并且有效负载数据不存在(这是响应中的错误)。

如何让我的 python 脚本生成与邮递员相同的服务器端对象?具体来说,我如何上传我的数据,使文件表示为:

谢谢。

【问题讨论】:

    标签: python-3.x django django-rest-framework upload postman


    【解决方案1】:

    事实证明,对 Postman 发布的对象的检查表明它正在使用多部分形式上传。环顾四周,我找到了一个相关问题的答案,将发布描述为多部分: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)
    

    【讨论】:

      猜你喜欢
      • 2018-09-04
      • 2020-09-30
      • 2013-03-16
      • 2018-07-19
      • 2012-03-07
      • 2019-10-16
      • 1970-01-01
      • 2012-09-21
      • 1970-01-01
      相关资源
      最近更新 更多