Skip to content

Commit bd23345

Browse files
committed
copilot suggestion: Move the root tempdir out of the for-loop
1 parent 84b575c commit bd23345

File tree

1 file changed

+14
-19
lines changed

1 file changed

+14
-19
lines changed

shiny/input_handler.py

Lines changed: 14 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -227,29 +227,24 @@ def _(value: Any, name: ResolvedId, session: Session) -> Any:
227227

228228
restore_ctx_dir = Path(restore_ctx.dir)
229229

230-
def cleanup_tempdir(tempdir_root: tempfile.TemporaryDirectory[str]):
231-
@session.on_ended
232-
def _():
233-
# Cleanup the temporary directory after the session ends
234-
tempdir_root.cleanup()
235-
236-
for f in value_list:
237-
assert f["datapath"] is not None and isinstance(f["datapath"], str)
230+
if len(value_list) > 0:
231+
tempdir_root = tempfile.TemporaryDirectory()
232+
session.on_ended(lambda: tempdir_root.cleanup())
238233

239-
data_path = f["datapath"]
234+
for f in value_list:
235+
assert f["datapath"] is not None and isinstance(f["datapath"], str)
240236

241-
# Prepend the persistent dir
242-
old_file = restore_ctx_dir / data_path
237+
data_path = f["datapath"]
243238

244-
# Copy the original file to a new temp dir, so that a restored session can't
245-
# modify the original.
246-
tempdir_root = tempfile.TemporaryDirectory()
247-
cleanup_tempdir(tempdir_root)
239+
# Prepend the persistent dir
240+
old_file = restore_ctx_dir / data_path
248241

249-
tempdir = Path(tempdir_root.name) / rand_hex(12)
250-
tempdir.mkdir(parents=True, exist_ok=True)
251-
f["datapath"] = str(tempdir / Path(data_path).name)
252-
shutil.copy2(old_file, f["datapath"])
242+
# Copy the original file to a new temp dir, so that a restored session can't
243+
# modify the original.
244+
tempdir = Path(tempdir_root.name) / rand_hex(12)
245+
tempdir.mkdir(parents=True, exist_ok=True)
246+
f["datapath"] = str(tempdir / Path(data_path).name)
247+
shutil.copy2(old_file, f["datapath"])
253248

254249
# Need to mark this input value with the correct serializer. When a file is
255250
# uploaded the usual way (instead of being restored), this occurs in

0 commit comments

Comments
 (0)