def add_body_part(self, data, mime_type, size=None):
    if isinstance(data, str):
      size = len(data)
    if size is None:
      # TODO: support chunked transfer if some of the body is of unknown size.
      raise UnknownSize('Each part of the body must have a known size.')
    if 'Content-Length' in self.headers:
      content_length = int(self.headers['Content-Length'])
    else:
      content_length = 0
    # If this is the first part added to the body, then this is not a multipart
    # request.
    if len(self._body_parts) == 0:
      self.headers['Content-Type'] = mime_type
      content_length = size
      self._body_parts.append(data)
    elif len(self._body_parts) == 1:
      # This is the first member in a mime-multipart request, so change the
      # _body_parts list to indicate a multipart payload.
      self._body_parts.insert(0, 'Media multipart posting')
      boundary_string = '\r\n--%s\r\n' % (MIME_BOUNDARY,)
      content_length += len(boundary_string) + size
      self._body_parts.insert(1, boundary_string)
      content_length += len('Media multipart posting')
      # Put the content type of the first part of the body into the multipart
      # payload.
      original_type_string = 'Content-Type: %s\r\n\r\n' % (
          self.headers['Content-Type'],)
      self._body_parts.insert(2, original_type_string)
      content_length += len(original_type_string)
      boundary_string = '\r\n--%s\r\n' % (MIME_BOUNDARY,)
      self._body_parts.append(boundary_string)
      content_length += len(boundary_string)
      # Change the headers to indicate this is now a mime multipart request.
      self.headers['Content-Type'] = 'multipart/related; boundary="%s"' % (
          MIME_BOUNDARY,)
      self.headers['MIME-version'] = '1.0'
      # Include the mime type of this part.
      type_string = 'Content-Type: %s\r\n\r\n' % (mime_type)
      self._body_parts.append(type_string)
      content_length += len(type_string)
      self._body_parts.append(data)
      ending_boundary_string = '\r\n--%s--' % (MIME_BOUNDARY,)
      self._body_parts.append(ending_boundary_string)
      content_length += len(ending_boundary_string)
    else:
      # This is a mime multipart request.
      boundary_string = '\r\n--%s\r\n' % (MIME_BOUNDARY,)
      self._body_parts.insert(-1, boundary_string)
      content_length += len(boundary_string) + size
      # Include the mime type of this part.
      type_string = 'Content-Type: %s\r\n\r\n' % (mime_type)
      self._body_parts.insert(-1, type_string)
      content_length += len(type_string)
      self._body_parts.insert(-1, data)
    self.headers['Content-Length'] = str(content_length)
  # I could add an "append_to_body_part" method as well.
Adds data to the HTTP request body.
dataset/ETHPy150Open CollabQ/CollabQ/vendor/atom/http_core.py/HttpRequest.add_body_part