|
14 | 14 |
|
15 | 15 | import base64 |
16 | 16 | import json |
| 17 | +import mimetypes |
| 18 | +from pathlib import Path |
17 | 19 | from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union, cast |
18 | 20 |
|
19 | 21 | from playwright.connection import ChannelOwner, from_channel, from_nullable_channel |
@@ -100,22 +102,36 @@ async def fulfill( |
100 | 102 | status: int = None, |
101 | 103 | headers: Dict[str, str] = None, |
102 | 104 | body: Union[str, bytes] = None, |
| 105 | + path: Union[str, Path] = None, |
103 | 106 | contentType: str = None, |
104 | 107 | ) -> None: |
105 | 108 | params = locals_to_params(locals()) |
106 | | - if contentType: |
107 | | - if headers is None: |
108 | | - headers = {} |
109 | | - headers["Content-Type"] = contentType |
110 | | - del params["contentType"] |
111 | | - if headers: |
112 | | - params["headers"] = serialize_headers(headers) |
| 109 | + length = 0 |
113 | 110 | if isinstance(body, str): |
114 | 111 | params["body"] = body |
115 | 112 | params["isBase64"] = False |
| 113 | + length = len(body.encode()) |
116 | 114 | elif isinstance(body, bytes): |
117 | 115 | params["body"] = base64.b64encode(body).decode() |
118 | 116 | params["isBase64"] = True |
| 117 | + length = len(body) |
| 118 | + elif path: |
| 119 | + del params["path"] |
| 120 | + file_content = Path(path).read_bytes() |
| 121 | + params["body"] = base64.b64encode(file_content).decode() |
| 122 | + params["isBase64"] = True |
| 123 | + length = len(file_content) |
| 124 | + |
| 125 | + headers = {k.lower(): str(v) for k, v in params.get("headers", {}).items()} |
| 126 | + if params.get("contentType"): |
| 127 | + headers["content-type"] = params["contentType"] |
| 128 | + elif path: |
| 129 | + headers["content-type"] = ( |
| 130 | + mimetypes.guess_type(str(Path(path)))[0] or "application/octet-stream" |
| 131 | + ) |
| 132 | + if length and "content-length" not in headers: |
| 133 | + headers["content-length"] = str(length) |
| 134 | + params["headers"] = serialize_headers(headers) |
119 | 135 | await self._channel.send("fulfill", params) |
120 | 136 |
|
121 | 137 | async def continue_( |
|
0 commit comments