简体   繁体   English

Python 中的文件的 POST 请求

[英]POST request with file in Python

Wanted to call Post method on my existing API which is working fine with PostMan, but now I wanted to pass the body content as the file type.想在我现有的 API 上调用 Post 方法,该方法与 PostMan 配合良好,但现在我想将正文内容作为文件类型传递。

Current, when I added the headers in the request.post it throw me 400 bad request exception but when I remove the headers it gives me 415 Media type which I am not able to understand, Could anyone please help me on this.当前,当我在 request.post 中添加标头时,它会抛出 400 错误请求异常,但是当我删除标头时,它会给我 415 媒体类型,我无法理解,谁能帮我解决这个问题。

My working code is mentioned here:我的工作代码在这里提到:

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)

My file, if I do the vi abs_path:我的文件,如果我执行 vi abs_path:

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

It is nothing but just plain JSON not array no nesting.它只是普通的 JSON 不是数组没有嵌套。

Below code is worked on me, really I am not 100% sure why this was not working before I have tried everything as well, I might have missed something which still I am not understood completely.下面的代码适用于我,真的我不是 100% 确定为什么在我尝试了所有东西之前它不起作用,我可能错过了一些我仍然不完全理解的东西。

Hope this might help few, in future.希望这对未来的少数人有所帮助。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM