|
12 | 12 | import platform |
13 | 13 | import warnings |
14 | 14 | import email.utils |
| 15 | +from urllib.parse import urlencode |
15 | 16 | from types import TracebackType |
16 | 17 | from random import random |
17 | 18 | from dataclasses import field, dataclass |
|
44 | 45 | from . import _exceptions |
45 | 46 | from ._qs import Querystring |
46 | 47 | from ._decoding import CodingRefused, BoundedDecoder, decoding_error |
47 | | -from ._files import to_httpx_files, async_to_httpx_files |
| 48 | +from ._files import to_httpx_files, read_form_files, async_to_httpx_files, async_read_form_files |
48 | 49 | from ._types import ( |
49 | 50 | Body, |
50 | 51 | Omit, |
@@ -320,6 +321,59 @@ def _merge_set_cookies(headers: httpx.Headers, response: httpx.Response, target: |
320 | 321 | headers["Cookie"] = "; ".join(pairs.values()) |
321 | 322 |
|
322 | 323 |
|
| 324 | +_FORM_URLENCODED = "application/x-www-form-urlencoded" |
| 325 | + |
| 326 | + |
| 327 | +def _is_form_urlencoded(content_type: object) -> bool: |
| 328 | + """Whether a `Content-Type` names the form media type, in any casing and with any parameters.""" |
| 329 | + return isinstance(content_type, str) and content_type.split(";", 1)[0].strip().lower() == _FORM_URLENCODED |
| 330 | + |
| 331 | + |
| 332 | +def _options_content_type(options: FinalRequestOptions) -> str | None: |
| 333 | + """The `Content-Type` a request's own headers set, matched case-insensitively, if any. |
| 334 | +
|
| 335 | + The last match wins, as it does when `_build_request` collapses duplicate entries, so both agree |
| 336 | + on whether a request is a form. |
| 337 | + """ |
| 338 | + if not is_given(options.headers): |
| 339 | + return None |
| 340 | + content_type: str | None = None |
| 341 | + for name, value in options.headers.items(): |
| 342 | + if name.lower() == "content-type" and isinstance(value, str): |
| 343 | + content_type = value |
| 344 | + return content_type |
| 345 | + |
| 346 | + |
| 347 | +def _form_text(value: object, array_format: str) -> object: |
| 348 | + """A form body prepared for the query encoder. |
| 349 | +
|
| 350 | + Each bytes value is decoded with `surrogateescape`: `Querystring` renders a leaf with `str()`, |
| 351 | + which spells bytes as `b'...'`, and encoding the pairs back with the same error handler keeps |
| 352 | + every byte as it was. An empty list is dropped, since `comma` would otherwise send `key=`, which a |
| 353 | + server reads as one empty element. Under `comma` a list holding objects or lists is refused: the |
| 354 | + format joins items with `str()`, so they would go out as Python repr. |
| 355 | + """ |
| 356 | + if isinstance(value, (bytes, bytearray)): |
| 357 | + return bytes(value).decode("utf-8", "surrogateescape") |
| 358 | + if is_mapping(value): |
| 359 | + return { |
| 360 | + key: _form_text(item, array_format) |
| 361 | + for key, item in value.items() |
| 362 | + if not ((is_list(item) or isinstance(item, tuple)) and len(cast("list[object]", item)) == 0) |
| 363 | + } |
| 364 | + if is_list(value) or isinstance(value, tuple): |
| 365 | + items = cast("list[object]", value) |
| 366 | + if array_format == "comma" and any( |
| 367 | + is_mapping(item) or is_list(item) or isinstance(item, tuple) for item in items |
| 368 | + ): |
| 369 | + raise TypeError( |
| 370 | + "A list of objects or lists cannot be sent in a form body under `arrayFormat: comma`;" |
| 371 | + " use `brackets`, `indices` or `repeat`." |
| 372 | + ) |
| 373 | + return [_form_text(item, array_format) for item in items] |
| 374 | + return value |
| 375 | + |
| 376 | + |
323 | 377 | def _describe_body(value: object) -> str: |
324 | 378 | """A request body as the debug log shows it: its shape and size, never its values. |
325 | 379 |
|
@@ -1151,9 +1205,33 @@ def _build_request( |
1151 | 1205 | params = _merge_mappings({**self._auth_query(options.security), **self.default_query}, options.params) |
1152 | 1206 | cookies = self._auth_cookies(options.security) |
1153 | 1207 | headers = self._build_headers(options, retries_taken=retries_taken, params=params, cookies=cookies) |
| 1208 | + content_types = headers.get_list("Content-Type") |
| 1209 | + if len(content_types) > 1: |
| 1210 | + # A `Content-Type` spelled in another casing than an earlier one is a second entry rather |
| 1211 | + # than a replacement, and two entries would join into a value neither encoder recognizes. |
| 1212 | + # The request's own headers (the method's, then the caller's `extra_headers`) win over a |
| 1213 | + # client-wide default, the same value `request()` read file fields for. |
| 1214 | + own_content_type = _options_content_type(options) |
| 1215 | + headers["Content-Type"] = own_content_type if own_content_type is not None else content_types[-1] |
1154 | 1216 | content_type = headers.get("Content-Type") |
1155 | 1217 | files = options.files |
1156 | 1218 |
|
| 1219 | + # A body under the form media type, in any casing, goes out encoded the way the query string |
| 1220 | + # is, through the client's own `qs`. A string or bytes body is a form already encoded and is |
| 1221 | + # sent as it is. |
| 1222 | + if _is_form_urlencoded(content_type) and json_data is not None and is_given(json_data): |
| 1223 | + if files: |
| 1224 | + # httpx sends `content` and drops `files` silently, so file parts would never arrive |
| 1225 | + raise TypeError("A form-urlencoded request body cannot carry multipart files") |
| 1226 | + if isinstance(json_data, str): |
| 1227 | + json_data = json_data.encode("utf-8") |
| 1228 | + elif not isinstance(json_data, bytes): |
| 1229 | + if not is_mapping(json_data): |
| 1230 | + raise TypeError( |
| 1231 | + f"Expected a mapping for a form-urlencoded request body but got {type(json_data)} instead." |
| 1232 | + ) |
| 1233 | + json_data = self._serialize_form_urlencoded(json_data) |
| 1234 | + |
1157 | 1235 | # If the given Content-Type header is multipart/form-data then it |
1158 | 1236 | # has to be removed so that httpx can generate the header with |
1159 | 1237 | # additional information for us as it has to be in this form |
@@ -1227,12 +1305,29 @@ def _build_request( |
1227 | 1305 | **kwargs, |
1228 | 1306 | ) |
1229 | 1307 |
|
| 1308 | + def _serialize_form_urlencoded(self, data: Mapping[str, object]) -> bytes: |
| 1309 | + """Encodes a form-urlencoded body exactly as the query string is encoded. |
| 1310 | +
|
| 1311 | + Lists follow the client's `array_format` and object keys its `nested_format`, and a boolean |
| 1312 | + goes out as `true` / `false`, all from `self.qs`. A space is written `+`, the form convention. |
| 1313 | + An empty string goes out as `key=`, which the query string drops, so a field can be cleared; |
| 1314 | + only `None` is left out. |
| 1315 | + A bytes value (a file field's contents, by now) is decoded with `surrogateescape` and encoded |
| 1316 | + back the same way, so bytes that are not UTF-8 reach the wire unchanged rather than as the |
| 1317 | + `b'...'` spelling `str()` would give them. |
| 1318 | + """ |
| 1319 | + qs = self.qs |
| 1320 | + items = qs.stringify_items(cast(Mapping[str, Any], _form_text(data, qs.array_format)), keep_empty=True) |
| 1321 | + return urlencode(items, encoding="utf-8", errors="surrogateescape").encode("ascii") |
| 1322 | + |
1230 | 1323 | def _serialize_multipartform(self, data: Mapping[object, object]) -> dict[str, object]: |
1231 | 1324 | items = self.qs.stringify_items( |
1232 | 1325 | # TODO: type ignore is required as stringify_items is well typed but we can't be |
1233 | 1326 | # well typed without heavy validation. |
1234 | 1327 | data, # type: ignore |
1235 | 1328 | array_format="brackets", |
| 1329 | + # multipart part names keep their bracketed form whatever the query string's nesting is |
| 1330 | + nested_format="brackets", |
1236 | 1331 | ) |
1237 | 1332 | serialized: dict[str, object] = {} |
1238 | 1333 | for key, value in items: |
@@ -1348,7 +1443,9 @@ def _validate_headers( |
1348 | 1443 |
|
1349 | 1444 | @property |
1350 | 1445 | def user_agent(self) -> str: |
1351 | | - return f"{self.__class__.__name__}/Python {self._version}" |
| 1446 | + # A literal rather than `self.__class__.__name__`, so the sync and async clients send the |
| 1447 | + # same product and a subclass cannot change it. |
| 1448 | + return f"Scalar/Python {self._version}" |
1352 | 1449 |
|
1353 | 1450 | @property |
1354 | 1451 | def base_url(self) -> URL: |
@@ -1676,6 +1773,10 @@ def request( |
1676 | 1773 | if input_options.idempotency_key is None and input_options.method.lower() != "get": |
1677 | 1774 | # ensure the idempotency key is reused between requests |
1678 | 1775 | input_options.idempotency_key = self._idempotency_key() |
| 1776 | + if _is_form_urlencoded(_options_content_type(input_options)): |
| 1777 | + # read file fields once, so every attempt sends the same contents |
| 1778 | + input_options.json_data = read_form_files(input_options.json_data) |
| 1779 | + input_options.extra_json = read_form_files(input_options.extra_json) |
1679 | 1780 |
|
1680 | 1781 | response: httpx.Response | None = None |
1681 | 1782 | max_retries = input_options.get_max_retries(self.max_retries) |
@@ -2315,6 +2416,10 @@ async def request( |
2315 | 2416 | if input_options.idempotency_key is None and input_options.method.lower() != "get": |
2316 | 2417 | # ensure the idempotency key is reused between requests |
2317 | 2418 | input_options.idempotency_key = self._idempotency_key() |
| 2419 | + if _is_form_urlencoded(_options_content_type(input_options)): |
| 2420 | + # read file fields once, so every attempt sends the same contents |
| 2421 | + input_options.json_data = await async_read_form_files(input_options.json_data) |
| 2422 | + input_options.extra_json = await async_read_form_files(input_options.extra_json) |
2318 | 2423 |
|
2319 | 2424 | response: httpx.Response | None = None |
2320 | 2425 | max_retries = input_options.get_max_retries(self.max_retries) |
|
0 commit comments