Reputation: 933
I'm porting code from NodeJS to python3. I want to post image binary data and text. How can I do it ? Thank you.
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"
}
})
My Wrong Python Code with 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)
I got 500 error.
Upvotes: 2
Views: 3347
Reputation: 1175
I use the Python3 library urllib.request
and it works perfectly for me. I also use a private key and certificate to upload files with SSL authentication. I show you how to do it in Python3
and its equivalent with the cURL
command.
Bash
version:
#!/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
version:
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())
I hope it helps you.
Upvotes: 1
Reputation: 2246
Files are supported in python3 requests module, here. This should work out for you.
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
Upvotes: 4