← pod_r5_v1i

requests_7433

resolved RESOLVED PASS · 8 tool calls · 39 s · psf/requests

Task input

Fix `prepare_body` stream detection for `__getattr__`-based file wrappers

Resolves #7432 .

Add `hasattr(data, "__iter__")` as a fallback stream detector:
```python
if (
    isinstance(data, Iterable) or hasattr(data, "__iter__")
) and not isinstance(data, (str, bytes, list, tuple, Mapping)):
```
This catches file-like objects that proxy their interface through `__getattr__`, restoring the 2.33.1 behavior without reverting the isinstance(Iterable) modernization for standard iterables.

Tool calls (9)

#ToolArgumentsResult
1run_command
{
 "command": "grep -rn 'prepare_body' src/requests/"
}
{"status": "ok", "stdout": "src/requests/models.py:442: self.prepare_body(data, files, json)\nsrc/requests/models.py:574: def prepare_body(\n", "stderr": "", "e
full
{"status": "ok", "stdout": "src/requests/models.py:442:        self.prepare_body(data, files, json)\nsrc/requests/models.py:574:    def prepare_body(\n", "stderr": "", "exit_code": 0}
2run_command
{
 "command": "sed -n '574,620p' src/requests/models.py"
}
{"status": "ok", "stdout": " def prepare_body(\n self, data: _t.DataType, files: _t.FilesType, json: _t.JsonType = None\n ) -> None:\n \"\"\"Prepares the given
full
{"status": "ok", "stdout": "    def prepare_body(\n        self, data: _t.DataType, files: _t.FilesType, json: _t.JsonType = None\n    ) -> None:\n        \"\"\"Prepares the given HTTP body data.\"\"\"\n\n        # Check if file, fo, generator, iterator.\n        # If not, run through normal process.\n\n        # Nottin' on you.\n        body = None\n        content_type = None\n\n        if not data and json is not None:\n            # urllib3 requires a bytes-like body. Python 2's json.dumps\n            # provides this natively, but Python 3 gives a Unicode string.\n            content_type = \"application/json\"\n\n            try:\n                body = complexjson.dumps(json, allow_nan=False)\n            except ValueError as ve:\n                raise InvalidJSONError(ve, request=self)\n\n            if not isinstance(body, bytes):\n                body = body.encode(\"utf-8\")\n\n        if isinstance(data, Iterable) and not isinstance(\n            data, (str, bytes, list, tuple, Mapping)\n        ):\n            try:\n                length = super_len(data)\n            except (TypeError, AttributeError, UnsupportedOperation):\n                length = None\n\n            body = data\n\n            if getattr(body, \"tell\", None) is not None:\n                # Record the current file position before reading.\n                # This will allow us to rewind a file in the event\n                # of a redirect.\n                try:\n                    self._body_position = body.tell()  # type: ignore[union-attr]  # guarded by getattr check\n                except OSError:\n                    # This differentiates from None, allowing us to catch\n                    # a failed `tell()` later when trying to rewind the body\n                    self._body_position = object()\n\n            if files:\n", "stderr": "", "exit_code": 0}
3run_command
{
 "command": "grep -n \"from typing import Iterable\" src/requests/models.py || grep -n \"from collections.abc import Iterable\" src/requests/models.py || grep -n \"from requests.compat import Iterable\" src/requests/models.py"
}
{"status": "error", "error_type": "CommandError", "error_message": "", "details": {"stdout": "", "stderr": "", "exit_code": 1}}
full
{"status": "error", "error_type": "CommandError", "error_message": "", "details": {"stdout": "", "stderr": "", "exit_code": 1}}
4run_command
{
 "command": "grep -n \"Iterable\" src/requests/models.py"
}
{"status": "ok", "stdout": "16:from collections.abc import Callable, Generator, Iterable, Iterator, Mapping\n259: self, event: str, hook: Iterable[_t.HookType]
full
{"status": "ok", "stdout": "16:from collections.abc import Callable, Generator, Iterable, Iterator, Mapping\n259:        self, event: str, hook: Iterable[_t.HookType] | _t.HookType\n599:        if isinstance(data, Iterable) and not isinstance(\n", "stderr": "", "exit_code": 0}
5run_command
{
 "command": "cd /workspace && python3 - <<'PY'\nfrom pathlib import Path\np = Path(\"src/requests/models.py\")\ns = p.read_text()\nold = \"\"\"        if isinstance(data, Iterable) and not isinstance(\n            data, (str, bytes, list, tuple, Mapping)\n        ):\"\"\"\nnew = \"\"\"        if (\n            isinstance(data, Iterable) or hasattr(data, \"__iter__\")\n        ) and not isinstance(data, (str, bytes, list, tuple, Mapping)):\"\"\"\nassert s.count(old) == 1, (\"old text found this many times:\", s.count(old))\nt = s.replace(old, new)\np.write_text(t)\nPY\n"
}
{"status": "ok", "stdout": "", "stderr": "", "exit_code": 0}
full
{"status": "ok", "stdout": "", "stderr": "", "exit_code": 0}
6run_command
{
 "command": "sed -n '599,602p' src/requests/models.py"
}
{"status": "ok", "stdout": " if (\n isinstance(data, Iterable) or hasattr(data, \"__iter__\")\n ) and not isinstance(data, (str, bytes, list, tuple, Mapping)):\
full
{"status": "ok", "stdout": "        if (\n            isinstance(data, Iterable) or hasattr(data, \"__iter__\")\n        ) and not isinstance(data, (str, bytes, list, tuple, Mapping)):\n            try:\n", "stderr": "", "exit_code": 0}
7run_command
{
 "command": "cd /workspace && python3 - <<'PY'\nfrom collections.abc import Iterable, Mapping\n\nclass Wrapper:\n    def __init__(self, data):\n        self.data = data\n    def __getattr__(self, name):\n        return getattr(self.data, name)\n\ndata_list = [1, 2, 3]\nwrapper = Wrapper(data_list)\n\n# This should be False if it's a list (which is in the excluded types)\ndef is_stream(data):\n    return (\n        isinstance(data, Iterable) or hasattr(data, \"__iter__\")\n    ) and not isinstance(data, (str, bytes, list, tuple, Mapping))\n\nprint(f\"List is stream: {is_stream(data_list)}\")\nprint(f\"Wrapper is stream: {is_stream(wrapper)}\")\nprint(f\"Is instance of Iterable: {isinstance(wrapper, Iterable)}\")\nprint(f\"Has __iter__: {hasattr(wrapper, '__iter__')}\")\nPY\n"
}
{"status": "ok", "stdout": "List is stream: False\nWrapper is stream: True\nIs instance of Iterable: False\nHas __iter__: True\n", "stderr": "", "exit_code": 0}
full
{"status": "ok", "stdout": "List is stream: False\nWrapper is stream: True\nIs instance of Iterable: False\nHas __iter__: True\n", "stderr": "", "exit_code": 0}
8run_command
{
 "command": "git diff"
}
{"status": "ok", "stdout": "diff --git a/src/requests/models.py b/src/requests/models.py\nindex 4142f2a4..f271e7e6 100644\n--- a/src/requests/models.py\n+++ b/s
full
{"status": "ok", "stdout": "diff --git a/src/requests/models.py b/src/requests/models.py\nindex 4142f2a4..f271e7e6 100644\n--- a/src/requests/models.py\n+++ b/src/requests/models.py\n@@ -596,9 +596,9 @@ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):\n             if not isinstance(body, bytes):\n                 body = body.encode(\"utf-8\")\n \n-        if isinstance(data, Iterable) and not isinstance(\n-            data, (str, bytes, list, tuple, Mapping)\n-        ):\n+        if (\n+            isinstance(data, Iterable) or hasattr(data, \"__iter__\")\n+        ) and not isinstance(data, (str, bytes, list, tuple, Mapping)):\n             try:\n                 length = super_len(data)\n             except (TypeError, AttributeError, UnsupportedOperation):\n", "stderr": "", "exit_code": 0}
9submit_patch
{}
{"status": "ok", "patch_size": 739, "files_changed": 1}
full
{"status": "ok", "patch_size": 739, "files_changed": 1}

Patch

diff --git a/src/requests/models.py b/src/requests/models.py
index 4142f2a4..f271e7e6 100644
--- a/src/requests/models.py
+++ b/src/requests/models.py
@@ -596,9 +596,9 @@ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
             if not isinstance(body, bytes):
                 body = body.encode("utf-8")
 
-        if isinstance(data, Iterable) and not isinstance(
-            data, (str, bytes, list, tuple, Mapping)
-        ):
+        if (
+            isinstance(data, Iterable) or hasattr(data, "__iter__")
+        ) and not isinstance(data, (str, bytes, list, tuple, Mapping)):
             try:
                 length = super_len(data)
             except (TypeError, AttributeError, UnsupportedOperation):

Test output

show
........................................................................ [ 21%]
.................................................spytest-httpbin server hit an exception serving request: [SSL: TLSV1_ALERT_UNKNOWN_CA] tlsv1 alert unknown ca (_ssl.c:1032)
attempting to ignore so the rest of the tests can run
...................... [ 42%]
........................................................................ [ 63%]
........................x............................................... [ 84%]
...................................................                      [100%]
=============================== warnings summary ===============================
../../../../../../../Users/jp/repos/kaggle-gemini-coding-agent-post-training/.envs/requests/lib/python3.13/site-packages/_pytest/config/__init__.py:1464
  /Users/jp/repos/kaggle-gemini-coding-agent-post-training/.envs/requests/lib/python3.13/site-packages/_pytest/config/__init__.py:1464: PytestConfigWarning: Unknown config option: timeout
  
    self._warn_or_fail_if_strict(f"Unknown config option: {key}\n")

tests/test_requests.py::TestRequests::test_set_basicauth[42-42]
tests/test_requests.py::TestRequests::test_set_basicauth[42-42]
  /tmp/swe_work/pod_r5_v1i/requests_7433/b/workspace/src/requests/auth.py:45: DeprecationWarning: Non-string usernames will no longer be supported in Requests 3.0.0. Please convert the object you've passed in (42) to a string or bytes object in the near future to avoid problems.
    warnings.warn(

tests/test_requests.py::TestRequests::test_set_basicauth[42-42]
tests/test_requests.py::TestRequests::test_set_basicauth[42-42]
  /tmp/swe_work/pod_r5_v1i/requests_7433/b/workspace/src/requests/auth.py:55: DeprecationWarning: Non-string passwords will no longer be supported in Requests 3.0.0. Please convert the object you've passed in (<class 'int'>) to a string or bytes object in the near future to avoid problems.
    warnings.warn(

tests/test_requests.py::TestRequests::test_set_basicauth[None-None]
tests/test_requests.py::TestRequests::test_set_basicauth[None-None]
  /tmp/swe_work/pod_r5_v1i/requests_7433/b/workspace/src/requests/auth.py:45: DeprecationWarning: Non-string usernames will no longer be supported in Requests 3.0.0. Please convert the object you've passed in (None) to a string or bytes object in the near future to avoid problems.
    warnings.warn(

tests/test_requests.py::TestRequests::test_set_basicauth[None-None]
tests/test_requests.py::TestRequests::test_set_basicauth[None-None]
  /tmp/swe_work/pod_r5_v1i/requests_7433/b/workspace/src/requests/auth.py:55: DeprecationWarning: Non-string passwords will no longer be supported in Requests 3.0.0. Please convert the object you've passed in (<class 'NoneType'>) to a string or bytes object in the near future to avoid problems.
    warnings.warn(

tests/test_requests.py::TestPreparingURLs::test_different_connection_pool_for_tls_settings_verify_True
tests/test_requests.py::TestPreparingURLs::test_different_connection_pool_for_tls_settings_verify_bundle_expired_cert
tests/test_requests.py::TestPreparingURLs::test_different_connection_pool_for_tls_settings_verify_bundle_unexpired_cert
tests/test_requests.py::TestPreparingURLs::test_different_connection_pool_for_mtls_settings
  /Users/jp/repos/kaggle-gemini-coding-agent-post-training/.envs/requests/lib/python3.13/site-packages/urllib3/connectionpool.py:1129: InsecureRequestWarning: Unverified HTTPS request is being made to host 'localhost'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#tls-warnings
    warnings.warn(

-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
337 passed, 1 skipped, 1 xfailed, 13 warnings in 39.00s
[2026-09-25 19:27:03,657] WARNING in core: flasgger is not installed; serving the static landing page at / and skipping the Swagger UI and /spec.json.
127.0.0.1 - - [25/Sep/2026 19:27:14] "GET /get HTTP/1.1" 200 272