Takes a multipart boundary encoded string and returns list of (key, value) tuples.
(
content_type: str | None, content: bytes
)
| 46 | |
| 47 | |
| 48 | def decode_multipart( |
| 49 | content_type: str | None, content: bytes |
| 50 | ) -> list[tuple[bytes, bytes]]: |
| 51 | """ |
| 52 | Takes a multipart boundary encoded string and returns list of (key, value) tuples. |
| 53 | """ |
| 54 | if content_type: |
| 55 | ct = headers.parse_content_type(content_type) |
| 56 | if not ct: |
| 57 | return [] |
| 58 | try: |
| 59 | boundary = ct[2]["boundary"].encode("ascii") |
| 60 | except (KeyError, UnicodeError): |
| 61 | return [] |
| 62 | |
| 63 | rx = re.compile(rb'\bname="([^"]+)"') |
| 64 | r = [] |
| 65 | if content is not None: |
| 66 | for i in content.split(b"--" + boundary): |
| 67 | parts = i.splitlines() |
| 68 | if len(parts) > 1 and parts[0][0:2] != b"--": |
| 69 | match = rx.search(parts[1]) |
| 70 | if match: |
| 71 | key = match.group(1) |
| 72 | value = b"".join(parts[3 + parts[2:].index(b"") :]) |
| 73 | r.append((key, value)) |
| 74 | return r |
| 75 | return [] |
| 76 | |
| 77 | |
| 78 | def encode(ct, parts): # pragma: no cover |