【问题标题】:POST request with file in Python在 Python 中使用文件 POST 请求
【发布时间】:2020-04-29 13:16:13
【问题描述】:

想在我现有的 API 上调用 Post 方法,该 API 可以与 PostMan 一起正常工作,但现在我想将正文内容作为文件类型传递。

当前,当我在 request.post 中添加标头时,它会抛出 400 错误请求异常,但是当我删除标头时,它会给我 415 媒体类型,我无法理解,谁能帮我解决这个问题。

这里提到了我的工作代码:

import os
import logging
import requests
from requests.auth import HTTPBasicAuth

config_directory = 'my-laptp-location\where-i-have\all-mt-files'
url = 'http://localhost:8080/api/v1/update'
usr = 'user'
passwd = 'pass'

for fileName in os.listdir(config_directory):
    print('Processing file: ', fileName)
    headers={'Content-type':'application/json', 'Accept':'application/json'}

    abs_path = os.path.abspath(os.path.join(config_directory, fileName))

    # files = {'file': (abs_path, open(abs_path, 'rb'), 'application/json', {'Expires': '0'})}
    # I tried the above as well but It also throw media type exception
    with open(abs_path, 'rb') as f:
        r = requests.post(calling_url, files={abs_path: f}, auth=HTTPBasicAuth(usr,passwd),headers=headers)
        print(r.status_code)

我的文件,如果我执行 vi abs_path:

{
  "key1": "value1",
  "key2": "value2",
  "key3": "value3",
}

它只是简单的 JSON,不是数组,没有嵌套。

【问题讨论】:

  • 您是否将正确的'Accept' 传递给您的标题?
  • Content-Type 标头需要为 multipart/form-data 以进行文件上传
  • 您应该为config_directory 使用r 类型文字,即:config_directory = r'my-laptp-location\where-i-have\all-mt-files',因为\a 是'\x07'(警报)而不是反斜杠后跟'a'。
  • 我尝试使用这两个评论从标题中删除 Accept 并按照@RishiDev 的建议添加了 multipart/form-data 但仍然有 415 作为不受支持的媒体类型,我已经更新了我的输入文件
  • 我已经尝试了互联网上的所有内容,但没有按预期工作 - 最后它说“不支持的媒体类型”415。不知道从这里做什么?

标签: python python-3.x python-requests


【解决方案1】:

下面的代码对我有用,真的我不是 100% 确定为什么在我尝试所有方法之前它不起作用,我可能错过了一些我仍然不完全理解的东西。

希望这对未来的少数人有所帮助。

import os
import logging
import requests
from requests.auth import HTTPBasicAuth

config_directory = 'my-laptp-location\where-i-have\all-mt-files'
url = 'http://localhost:8080/api/v1/update'
usr = 'user'
passwd = 'pass'

for fileName in os.listdir(config_directory):
    print('Processing file: ', fileName)
    headers={'Content-type':'application/json'}

    abs_path = os.path.abspath(os.path.join(config_directory, fileName))

    with open(abs_path, 'rb') as f:
        r = requests.post(calling_url, headers=headers, auth=HTTPBasicAuth(usr, passwd), data=f)
        print(r.status_code)
        print(r.content)

【讨论】:

    猜你喜欢
    • 2018-02-09
    • 1970-01-01
    • 2017-11-28
    • 2013-04-15
    • 1970-01-01
    • 1970-01-01
    • 2014-10-10
    • 2018-06-08
    相关资源
    最近更新 更多