Skip to content

Commit e7de262

Browse files
committed
Fix _encode_files detection for __getattr__-based file wrappers
1 parent 1190afd commit e7de262

2 files changed

Lines changed: 28 additions & 1 deletion

File tree

src/requests/models.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -236,7 +236,8 @@ def _encode_files(
236236

237237
if isinstance(fp, (str, bytes, bytearray)):
238238
fdata = fp
239-
elif isinstance(fp, _SupportsRead): # type: ignore[reportUnnecessaryIsInstance] # defensive check for untyped callers
239+
# data that proxies attributes to underlying objects needs hasattr
240+
elif isinstance(fp, _SupportsRead) or hasattr(fp, 'read'): # type: ignore[reportUnnecessaryIsInstance] # defensive check for untyped callers
240241
fdata = fp.read()
241242
elif fp is None: # defensive check for untyped callers
242243
continue

tests/test_requests.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1087,6 +1087,32 @@ def test_different_encodings_dont_break_post(self, httpbin):
10871087
)
10881088
assert r.status_code == 200
10891089

1090+
def test_post_tempfile(self, httpbin):
1091+
with tempfile.TemporaryFile(mode="w+") as f:
1092+
f.write("temp file contents\n")
1093+
f.seek(0)
1094+
r = requests.post(
1095+
httpbin("post"),
1096+
data={"stuff": json.dumps({"a": 123})},
1097+
params={"blah": "asdf1234"},
1098+
files={"file": f},
1099+
)
1100+
assert r.status_code == 200
1101+
assert r.json()["files"]["file"] == "temp file contents\n"
1102+
1103+
def test_post_named_tempfile(self, httpbin):
1104+
with tempfile.NamedTemporaryFile(mode="w+") as f:
1105+
f.write("named temp file contents\n")
1106+
f.seek(0)
1107+
r = requests.post(
1108+
httpbin("post"),
1109+
data={"stuff": json.dumps({"a": 123})},
1110+
params={"blah": "asdf1234"},
1111+
files={"file": f},
1112+
)
1113+
assert r.status_code == 200
1114+
assert r.json()["files"]["file"] == "named temp file contents\n"
1115+
10901116
@pytest.mark.parametrize(
10911117
"data",
10921118
(

0 commit comments

Comments
 (0)