如何在python3和`requests`上发布图像和文本MultipartForm?

时间:2018-05-08 03:15:06

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

我正在将代码从NodeJS移植到python3。 我想发布图像二进制数据和文本。 我该怎么做 ?谢谢。

的NodeJS

filePath = "xxx.jpeg"
text = "xxx"
return chakram.request("POST", "http://xxx",
     { "multipart" : [
           { "body" : fs.createReadStream(filePath),
             "Content-Type" : "image/jpeg",
             "Content-Disposition" : "name='file'; filename='" + filePath + "'"
           },
           { "body" : JSON.stringify(this.RequestData(text)),
             "Content-Type" : "application/specified-content-type-xxx"
           }
       ],
       "headers" : {
           "Authorization" : "xxx"
       }
     })

我错误的Python代码requests

filePath = "xxx.jpeg"
text = "xxx"
headers = {
    "Authorization" : "xxx"
}

binary_data = None
with open(file_path, 'rb') as fp:
    binary_data = fp.read()

request_body = {
    "text": text,
    "type": "message",
    "from": {
        "id": "user1"
    }
}
files = {
    "file": (filePath, binary_data, 'image/jpeg'),
    "": ("", request_body, "application/specified-content-type-xxx")
}
resp = requests.post("http://xxx", files=files, headers=headers)

我收到500错误。

2 个答案:

答案 0 :(得分:0)

python3请求模块here支持文件。这应该适合你。

import requests

url = "http://xxx"

# just set files to a list of tuples of (form_field_name, file_info)
multiple_files = [
        ('images', ('xxx.jpeg', open('xxx.jpeg', 'rb'), 'image/png')),
        ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))
]

text_data = {"key":"value"}
headers = {
    "Authorization" : "xxx",
    "Content-Type": "application/json"
}
r = requests.post(url, files=multiple_files, data=text_data, headers=headers)
r.text

答案 1 :(得分:0)

我使用Python3库urllib.request,它非常适合我。我还使用私钥和证书通过SSL身份验证上传文件。我将向您展示如何在Python3中进行操作,以及与cURL命令等效的操作。

Bash版本:

#!/bin/bash

KEY="my_key.pem"
CERT="my_cert.pem"
PASSWORD="XXXXXXX"
URL="https://put_here_your_host.com"
FILE="my_file.txt" # or .pdf, .tar.gz, etc.

curl -k --cert $CERT:$PASSWORD --key $KEY $URL -X POST -H "xxx : xxx, yyy: yyy" -T $FILE

Python3版本:

import ssl
import urllib.request

# Set global
key         = 'my_key.pem'
cert        = 'my_cert.pem'
password    = 'XXXXXXX'
url         = 'https://put_here_your_host.com'
file        = 'my_file.txt' # or .pdf, .tar.gz, etc.

# Security block. You can skip this block if you do not need it.
context = ssl.create_default_context()
context.load_cert_chain(cert, keyfile=key, password=password)
opener = urllib.request.build_opener(urllib.request.HTTPSHandler(context=context))
urllib.request.install_opener(opener)

# Set request with headers.
headers = {
    'xxx' : 'xxx',
    'yyy': 'yyy'
}
request = urllib.request.Request(url, headers=headers)

# Post your file.
urllib.request.urlopen(request, open(file, 'rb').read())

希望对您有帮助。