【问题标题】:How to post a file to Django/DRF using python requests如何使用 python 请求将文件发布到 Django/DRF
【发布时间】:2021-08-28 19:47:45
【问题描述】:

我有以下代码将 json 数据集/文件发布到 Django/DRF API 数据库。

我收到错误消息

{"ohlc":["No file was submitted."]}

我做错了什么?

test_url = "http://localhost:8000/stocks/aapl/price/"

test_file = {
    "aapl": open("./ohlc_aapl.json", "rb")
}

payload = x.to_dict(orient='records')

r = requests.post(test_url, 
                  files=test_file,
                  json=payload)

payload 如下所示

[{'date': '2020-08-27 00:00:00',
  'open': 508.57,
  'high': 509.94,
  'low': 495.33,
  'close': 500.04,
  'adjusted_close': 124.2111,
  'volume': 155552408},
 {'date': '2020-08-28 00:00:00',
  'open': 504.05,
  'high': 505.77,
  'low': 498.31,
  'close': 499.23,
  'adjusted_close': 124.0099,
  'volume': 187629920},
   ...

【问题讨论】:

  • 错误是说没有文件被提交,所以问题出在test_file而不是payload,test_file中有什么?

标签: python django post django-rest-framework python-requests


【解决方案1】:

我认为问题在于您的序列化程序需要 ohlc 字段下的文件,而您发布的是 aapl

试试这个。

        fname = "ohlc_aapl.json"
        with open(f"./{fname}", "rb") as fb:
            response = requests.post(
                url=test_url,
                files={
                    'ohlc': (fname, fb)
                },
                json=payload,
            )

【讨论】:

    猜你喜欢
    • 2020-05-21
    • 2014-06-01
    • 2018-10-29
    • 2022-12-01
    • 2017-07-08
    • 1970-01-01
    • 2017-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多