Encodes a set of parameters (typically a name/value list) and a set of files (a list of (name, filename, file_body, mimetype)) into a typical POST body, returning the (content_type, body).
(self, params, files)
| 465 | delete_json = utils.json_method('DELETE') |
| 466 | |
| 467 | def encode_multipart(self, params, files): |
| 468 | """ |
| 469 | Encodes a set of parameters (typically a name/value list) and |
| 470 | a set of files (a list of (name, filename, file_body, mimetype)) into a |
| 471 | typical POST body, returning the (content_type, body). |
| 472 | |
| 473 | """ |
| 474 | boundary = to_bytes(str(random.random()))[2:] |
| 475 | boundary = b'----------a_BoUnDaRy' + boundary + b'$' |
| 476 | lines = [] |
| 477 | |
| 478 | def _append_file(file_info): |
| 479 | key, filename, value, fcontent = self._get_file_info(file_info) |
| 480 | if isinstance(key, str): |
| 481 | try: |
| 482 | key = key.encode('ascii') |
| 483 | except: # pragma: no cover |
| 484 | raise # file name must be ascii |
| 485 | if isinstance(filename, str): |
| 486 | try: |
| 487 | filename = filename.encode('utf8') |
| 488 | except: # pragma: no cover |
| 489 | raise # file name must be ascii or utf8 |
| 490 | if not fcontent: |
| 491 | fcontent = mimetypes.guess_type(filename.decode('utf8'))[0] |
| 492 | fcontent = to_bytes(fcontent) |
| 493 | fcontent = fcontent or b'application/octet-stream' |
| 494 | lines.extend([ |
| 495 | b'--' + boundary, |
| 496 | b'Content-Disposition: form-data; ' + |
| 497 | b'name="' + key + b'"; filename="' + filename + b'"', |
| 498 | b'Content-Type: ' + fcontent, b'', value]) |
| 499 | |
| 500 | for key, value in params: |
| 501 | if isinstance(key, str): |
| 502 | try: |
| 503 | key = key.encode('ascii') |
| 504 | except: # pragma: no cover |
| 505 | raise # field name are always ascii |
| 506 | if isinstance(value, forms.File): |
| 507 | if "multiple" in value.attrs: |
| 508 | for file in value.value: |
| 509 | _append_file([key] + list(file)) |
| 510 | elif value.value: |
| 511 | _append_file([key] + list(value.value)) |
| 512 | else: |
| 513 | # If no file was uploaded simulate an empty file with no |
| 514 | # name like real browsers do: |
| 515 | _append_file([key, b'', b'']) |
| 516 | elif isinstance(value, forms.Upload): |
| 517 | file_info = [key, value.filename] |
| 518 | if value.content is not None: |
| 519 | file_info.append(value.content) |
| 520 | if value.content_type is not None: |
| 521 | file_info.append(value.content_type) |
| 522 | _append_file(file_info) |
| 523 | else: |
| 524 | if isinstance(value, int): |