askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
danq9
signup: the person chooses the password and name on the confirm page
83c7aa6
2 weeks, 5 days ago
History
object_multipart.py · 2.9 KB · 84 lines
| 1 | """Multipart form parsing for object execution, standard library only. |
| 2 | |
| 3 | Browser upload forms post `multipart/form-data`. Text parts become plain |
| 4 | payload fields; file parts are collected under a `_files` mapping with the |
| 5 | content base64-encoded so the payload stays JSON-serializable across the |
| 6 | subprocess execution boundary: |
| 7 | |
| 8 | request["photo_caption"] # text field |
| 9 | request["_files"]["photo"]["filename"] |
| 10 | request["_files"]["photo"]["content_type"] |
| 11 | request["_files"]["photo"]["size"] |
| 12 | base64.b64decode(request["_files"]["photo"]["content_base64"]) |
| 13 | |
| 14 | Request bodies are already capped by DBBASIC_MAX_REQUEST_BYTES before parsing. |
| 15 | """ |
| 16 | |
| 17 | from __future__ import annotations |
| 18 | |
| 19 | import base64 |
| 20 | from email import policy |
| 21 | from email.parser import BytesParser |
| 22 | from typing import Any |
| 23 | |
| 24 | FILES_KEY = "_files" |
| 25 | |
| 26 | |
| 27 | class InvalidMultipartError(ValueError): |
| 28 | """Raised when a multipart body cannot be parsed.""" |
| 29 | |
| 30 | |
| 31 | def is_multipart_content_type(content_type: str) -> bool: |
| 32 | return content_type.split(";")[0].strip().lower() == "multipart/form-data" |
| 33 | |
| 34 | |
| 35 | def parse_multipart(body: bytes, content_type: str) -> dict[str, Any]: |
| 36 | """Parse one multipart/form-data body into an object payload dict.""" |
| 37 | if not is_multipart_content_type(content_type): |
| 38 | raise InvalidMultipartError("Content type is not multipart/form-data") |
| 39 | if "boundary=" not in content_type: |
| 40 | raise InvalidMultipartError("Multipart body is missing a boundary") |
| 41 | |
| 42 | header = f"Content-Type: {content_type}\r\nMIME-Version: 1.0\r\n\r\n".encode("latin-1") |
| 43 | try: |
| 44 | message = BytesParser(policy=policy.HTTP).parsebytes(header + body) |
| 45 | except Exception as exc: # email parser errors are varied |
| 46 | raise InvalidMultipartError(f"Could not parse multipart body: {exc}") from exc |
| 47 | |
| 48 | if not message.is_multipart(): |
| 49 | raise InvalidMultipartError("Multipart body has no parts") |
| 50 | |
| 51 | payload: dict[str, Any] = {} |
| 52 | files: dict[str, dict[str, Any]] = {} |
| 53 | |
| 54 | for part in message.iter_parts(): |
| 55 | disposition = part.get("Content-Disposition", "") |
| 56 | if "form-data" not in disposition: |
| 57 | continue |
| 58 | name = part.get_param("name", header="Content-Disposition") |
| 59 | if not name: |
| 60 | continue |
| 61 | |
| 62 | filename = part.get_filename() |
| 63 | content = part.get_payload(decode=True) |
| 64 | if content is None: |
| 65 | content = b"" |
| 66 | |
| 67 | if filename is not None: |
| 68 | files[str(name)] = { |
| 69 | "filename": str(filename), |
| 70 | "content_type": part.get_content_type(), |
| 71 | "size": len(content), |
| 72 | "content_base64": base64.b64encode(content).decode("ascii"), |
| 73 | } |
| 74 | else: |
| 75 | try: |
| 76 | payload[str(name)] = content.decode("utf-8") |
| 77 | except UnicodeDecodeError as exc: |
| 78 | raise InvalidMultipartError( |
| 79 | f"Form field {name} is not valid UTF-8 text" |
| 80 | ) from exc |
| 81 | |
| 82 | if files: |
| 83 | payload[FILES_KEY] = files |
| 84 | return payload |