Skip to content

Commit d5e0175

Browse files
Fix to_netcdf usage to be more future-proof (#103)
1 parent 0748bc7 commit d5e0175

File tree

1 file changed

+12
-1
lines changed

1 file changed

+12
-1
lines changed

src/openlifu/plan/solution.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import base64
44
import json
5+
import tempfile
56
from dataclasses import asdict, dataclass, field
67
from datetime import datetime
78
from pathlib import Path
@@ -429,7 +430,17 @@ def to_json(self, include_simulation_data: bool, compact: bool) -> str:
429430

430431
if include_simulation_data:
431432
# Serialize xarray dataset into a string
432-
solution_dict['simulation_result'] = base64.b64encode(self.simulation_result.to_netcdf(engine='scipy')).decode('utf-8')
433+
with tempfile.NamedTemporaryFile(suffix=".nc", delete=False) as tmp:
434+
tmp_path = Path(tmp.name)
435+
try:
436+
self.simulation_result.to_netcdf(tmp_path, engine='scipy')
437+
# (to_netcdf can write to general byte stream instead of a file, but its behavior is changing
438+
# in a way that will likely break how we do it in only some python versions,
439+
# so writing to a tempfile is a fool proof solution across versions until to_netcdf stabilizes in its behavior)
440+
raw_bytes = tmp_path.read_bytes()
441+
finally:
442+
tmp_path.unlink(missing_ok=True)
443+
solution_dict['simulation_result'] = base64.b64encode(raw_bytes).decode('utf-8')
433444
else:
434445
solution_dict.pop('simulation_result')
435446

0 commit comments

Comments
 (0)