def do_upload(self, filename, url, params=None, fileobj=None, timeout=None):
"""Performs a file upload to the given URL with the given parameters, signed with OAuth.
:param timeout: optional request timeout, in seconds.
:type timeout: float
@return: the response content
"""
# work-around to allow non-ascii characters in file name
# Flickr doesn't store the name but does use it as a default title
if 'title' not in params:
params['title'] = os.path.basename(filename).encode('utf8')
# work-around for Flickr expecting 'photo' to be excluded
# from the oauth signature:
# 1. create a dummy request without 'photo'
# 2. create real request and use auth headers from the dummy one
dummy_req = requests.Request('POST', url, data=params,
auth=self.oauth)
prepared = dummy_req.prepare()
headers = prepared.headers
self.log.debug('do_upload: prepared headers = %s', headers)
if not fileobj:
fileobj = open(filename, 'rb')
params['photo'] = ('dummy name', fileobj)
m = MultipartEncoder(fields=params)
auth = {'Authorization': headers.get('Authorization'),
'Content-Type': m.content_type}
self.log.debug('POST %s', auth)
req = self.session.post(url, data=m, headers=auth, timeout=timeout or self.default_timeout)
# check the response headers / status code.
if req.status_code != 200:
self.log.error('do_upload: Status code %i received, content:', req.status_code)
for part in req.text.split('&'):
self.log.error(' %s', urllib_parse.unquote(part))
raise exceptions.FlickrError('do_upload: Status code %s received' % req.status_code)
return req.content
评论列表
文章目录