My goal is create a HTTP request (headers and body) manually. It has to look like this:
Some-Header1: some value1
Some-Header2: some value2
Some-Header3: some value3
-------------MyBoundary
Content-Disposition: form-data; name="file_content_0"; filename="123.pdf"
Content-Length: 93
Content-Type: application/pdf
Content-Transfer-Encoding: binary
==== here is the binary data of 123.pdf ====
==== here is the binary data of 123.pdf ====
==== here is the binary data of 123.pdf ====
==== here is the binary data of 123.pdf ====
-------------MyBoundary--
I've found out that this is the only way to send a file to a web service through its API because I sniffed the traffic of a script in Ruby doing that and the it turned out to look like I've shown above.
So the headers such as "Some-Header1" and other - are the plain text headers. Notice that there is also "-------------MyBoundary--" after "==== here is the binary data of 123.pdf ===="
But "==== here is the binary data of 123.pdf ====" is binary data.
The question is, how do I chain (combine) the plain text data with the binary data?
P.S. I've been trying to achieve this by the standard libraries such a python-requests and failed. I don't consider using them again at this point. For now I only need to know how to combine the plain text and binary data.
UPDATE:
How can I easily embed a binary data to a string?
import textwrap
body_headers = textwrap.dedent(
"""
-------------MyBoundary
Content-Disposition: form-data; name="file_content_0"; filename="a.c"
Content-Length: 1234
Content-Type: image/jpeg
Content-Transfer-Encoding: binary
%b ??? -> to indicate that a binary data will be placed here
-------------MyBoundary--
"""
) % binary_data" #???
UPDATE2:
text1 = textwrap.dedent(
"""
-------------MyBoundary
Content-Disposition: form-data; name="file_content_0"; filename="a.pdf"
Content-Length: 1234
Content-Type: image/jpeg
Content-Transfer-Encoding: binary
replace_me
-------------MyBoundary--
"""
)
with open("test1.pdf", "rb") as file_hander:
binary_data = file_hander.read()
print (isinstance(binary_data, str)) # True
print (isinstance("replace_me", str)) # True
print text1.replace("replace_me", binary_data) # --> [Decode error - output not utf-8]
print text1.replace("replace_me", binary_data).encode("utf-8") # exception
Error:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 195: ordinal not in range(128)
And this also gives me an exception:
print unicode(text1.replace("replace_me", binary_data), "utf-8")
# UnicodeDecodeError: 'utf8' codec can't decode byte 0xc4 in position 195: invalid continuation byte