import uuid


def _multipartBody (*parts):
  """
  Builds a multipart/form-data (RFC 2388) document out of a list of
  constituent parts.  Each part is either a 2-tuple (name, value) or a
  4-tuple (name, filename, contentType, value).  Returns a tuple
  (document, boundary).
  """
  while True:
    boundary = "BOUNDARY_%s" % uuid.uuid1().hex
    collision = False
    for p in parts:
      for e in p:
        if boundary in e: collision = True
    if not collision: break
  body = []
  for p in parts:
    body.append("--" + boundary)
    if len(p) == 2:
      body.append("Content-Disposition: form-data; name=\"%s\"" % p[0])
      body.append("")
      body.append(p[1])
    else:
      body.append(("Content-Disposition: form-data; name=\"%s\"; " +\
        "filename=\"%s\"") % (p[0], p[1]))
      body.append("Content-Type: " + p[2])
      body.append("")
      body.append(p[3])
  body.append("--%s--" % boundary)
  return ("\r\n".join(body), boundary)