1👍
Using the BlackBlaze python directory pusher for reference and assuming that file_content
is a file-like object (like Django’s UploadedFile
), I’d suggest you try passing the file-like object file_content
rather than string file_contents
to the urllib2.Request
constructor.
Relevant bits from the file I linked are:
class OpenUrl(object):
"""
Context manager that handles an open urllib2.Request, and provides
the file-like object that is the response.
"""
def __init__(self, url, data, headers):
self.url = url
self.data = data
self.headers = headers
self.file = None
def __enter__(self):
try:
request = urllib2.Request(self.url, self.data, self.headers)
self.file = urllib2.urlopen(request)
return self.file
except urllib2.HTTPError as e:
pass # edited
and
def post_file(url, headers, file_path):
"""Posts the contents of the file to the URL.
URL-encodes all of the data in the headers before sending.
"""
with open(file_path, 'rb') as data_file:
if 'Content-Length' not in headers:
headers['Content-Length'] = str(os.path.getsize(file_path))
encoded_headers = dict(
(k, b2_url_encode(v)) for (k, v) in headers.iteritems()
)
with OpenUrl(url, data_file, encoded_headers) as response_file:
json_text = response_file.read()
return json.loads(json_text)
Source:stackexchange.com