diff --git a/src/requests/models.py b/src/requests/models.py index c4cc028e0d..ebeba1e39f 100644 --- a/src/requests/models.py +++ b/src/requests/models.py @@ -236,7 +236,9 @@ def _encode_files( if isinstance(fp, (str, bytes, bytearray)): fdata = fp - elif isinstance(fp, _SupportsRead): # defensive check for untyped callers + # data that proxies attributes to underlying objects needs hasattr + # defensive check for untyped callers + elif isinstance(fp, _SupportsRead) or hasattr(fp, "read"): fdata = fp.read() elif fp is None: # defensive check for untyped callers continue diff --git a/tests/test_requests.py b/tests/test_requests.py index 571535fe79..2cea2fe8d9 100644 --- a/tests/test_requests.py +++ b/tests/test_requests.py @@ -1087,6 +1087,17 @@ def test_different_encodings_dont_break_post(self, httpbin): ) assert r.status_code == 200 + def test_post_named_tempfile(self, httpbin): + with tempfile.NamedTemporaryFile(mode="w+") as f: + f.write("named temp file contents\n") + f.seek(0) + r = requests.post( + httpbin("post"), + files={"file": f}, + ) + assert r.status_code == 200 + assert r.json()["files"]["file"] == "named temp file contents\n" + @pytest.mark.parametrize( "data", (