+ # Build the uri.
+ uriparts = []
+ for uripart in self.uriparts:
+ # If this part matches a keyword argument, use the
+ # supplied value otherwise, just use the part.
+ uriparts.append(str(kwargs.pop(uripart, uripart)))
+ uri = '/'.join(uriparts)
+
+ method = kwargs.pop('_method', None)
+ if not method:
+ method = "GET"
+ for action in POST_ACTIONS:
+ if re.search("%s(/\d+)?$" % action, uri):
+ method = "POST"
+ break
+
+ # If an id kwarg is present and there is no id to fill in in
+ # the list of uriparts, assume the id goes at the end.
+ id = kwargs.pop('id', None)
+ if id:
+ uri += "/%s" % (id)
+
+ # If an _id kwarg is present, this is treated as id as a CGI
+ # param.
+ _id = kwargs.pop('_id', None)
+ if _id:
+ kwargs['id'] = _id
+
+ # If an _timeout is specified in kwargs, use it
+ _timeout = kwargs.pop('_timeout', None)
+
+ secure_str = ''
+ if self.secure:
+ secure_str = 's'
+ dot = ""
+ if self.format:
+ dot = "."
+ uriBase = "http%s://%s/%s%s%s" % (
+ secure_str, self.domain, uri, dot, self.format)
+
+ # Catch media arguments to handle oauth query differently for multipart
+ media = None
+ for arg in ['media[]', 'banner', 'image']:
+ if arg in kwargs:
+ media = kwargs.pop(arg)
+ # Check if argument tells whether img is already base64 encoded
+ b64_convert = True
+ if "_base64" in kwargs:
+ b64_convert = not kwargs.pop("_base64")
+ if b64_convert:
+ import base64
+ media = base64.b64encode(media)
+ mediafield = arg
+ break
+
+ headers = {'Accept-Encoding': 'gzip'} if self.gzip else dict()
+ body = None
+ arg_data = None
+ if self.auth:
+ headers.update(self.auth.generate_headers())
+ # Use urlencoded oauth args with no params when sending media
+ # via multipart and send it directly via uri even for post
+ arg_data = self.auth.encode_params(
+ uriBase, method, {} if media else kwargs)
+ if method == 'GET' or media:
+ uriBase += '?' + arg_data
+ else:
+ body = arg_data.encode('utf8')
+
+ # Handle query as multipart when sending media
+ if media:
+ BOUNDARY = "###Python-Twitter###"
+ bod = []
+ bod.append('--' + BOUNDARY)
+ bod.append(
+ 'Content-Disposition: form-data; name="%s"' % mediafield)
+ bod.append('Content-Transfer-Encoding: base64')
+ bod.append('')
+ bod.append(media)
+ for k, v in kwargs.items():
+ bod.append('--' + BOUNDARY)
+ bod.append('Content-Disposition: form-data; name="%s"' % k)
+ bod.append('')
+ bod.append(v)
+ bod.append('--' + BOUNDARY + '--')
+ body = '\r\n'.join(bod)
+ headers['Content-Type'] = \
+ 'multipart/form-data; boundary=%s' % BOUNDARY
+
+ req = urllib_request.Request(uriBase, body, headers)
+ return self._handle_response(req, uri, arg_data, _timeout)
+
+ def _handle_response(self, req, uri, arg_data, _timeout=None):
+ kwargs = {}
+ if _timeout:
+ kwargs['timeout'] = _timeout