Skip to content

Commit daf7aa7

Browse files
committed
EnvironBuilder closes all files
1 parent 9006ebd commit daf7aa7

File tree

4 files changed

+19
-13
lines changed

4 files changed

+19
-13
lines changed

CHANGES.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ Unreleased
1616
the request was ``POST``. :pr:`3091`
1717
- The test client does not handle ``305`` as a redirect, as it is no longer
1818
part of the HTTP spec. :pr:`3091`
19+
- ``EnvironBuilder.close`` closes all open files in ``files`` rather than only
20+
the first for each key. :pr:`3091`
1921

2022

2123
Version 3.1.5

src/werkzeug/datastructures/file_storage.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,16 @@ def add_file(
204204

205205
self.add(name, FileStorage(file_obj, filename, name, content_type))
206206

207+
def close(self) -> None:
208+
"""Call :meth:`~FileStorage.close` on every open file.
209+
210+
.. versionadded:: 3.2
211+
"""
212+
for values in self.listvalues():
213+
for value in values:
214+
if not value.closed:
215+
value.close()
216+
207217

208218
# circular dependencies
209219
from .. import http # noqa: E402

src/werkzeug/test.py

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -653,15 +653,10 @@ def close(self) -> None:
653653
"""
654654
if self.closed:
655655
return
656-
try:
657-
files = self.files.values()
658-
except AttributeError:
659-
files = ()
660-
for f in files:
661-
try:
662-
f.close()
663-
except Exception:
664-
pass
656+
657+
if self._files is not None:
658+
self.files.close()
659+
665660
self.closed = True
666661

667662
def get_environ(self) -> WSGIEnvironment:

tests/test_test.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import io
12
import json
23
import sys
34
from functools import partial
@@ -425,12 +426,10 @@ def test_builder_from_environ():
425426
def test_file_closing():
426427
closed = []
427428

428-
class SpecialInput:
429-
def read(self, size):
430-
return b""
431-
429+
class SpecialInput(io.BytesIO):
432430
def close(self):
433431
closed.append(self)
432+
super().close()
434433

435434
create_environ(data={"foo": SpecialInput()})
436435
assert len(closed) == 1

0 commit comments

Comments
 (0)