fix: пустой временный файл при отсутствии циклов в шаблоне (Package not found)
expand_loops_in_zip возвращал путь к пустому tmp-файлу, если в шаблоне не было маркеров <!-- loop:... -->. python-docx падал с 'Package not found'. Теперь при отсутствии циклов возвращается исходный шаблон, tmp удаляется. Тесты: без циклов, с циклом, вложенные циклы — всё ок.
This commit is contained in:
@@ -86,6 +86,7 @@ def expand_loops_in_zip(docx_path: str, loops: Dict[str, List[Dict]]) -> str:
|
||||
tmp = tempfile.NamedTemporaryFile(delete=False, suffix='.docx')
|
||||
tmp.close()
|
||||
|
||||
wrote = False # была ли хоть одна запись в tmp
|
||||
max_passes = 30
|
||||
for _ in range(max_passes):
|
||||
# Читаем ВСЕ файлы из исходного ZIP
|
||||
@@ -144,6 +145,7 @@ def expand_loops_in_zip(docx_path: str, loops: Dict[str, List[Dict]]) -> str:
|
||||
with zipfile.ZipFile(tmp.name, 'w', zipfile.ZIP_DEFLATED) as z:
|
||||
for name, data in all_files.items():
|
||||
z.writestr(name, data)
|
||||
wrote = True
|
||||
continue
|
||||
|
||||
# Извлекаем шаблон (всё между start и end маркерами)
|
||||
@@ -170,6 +172,16 @@ def expand_loops_in_zip(docx_path: str, loops: Dict[str, List[Dict]]) -> str:
|
||||
with zipfile.ZipFile(tmp.name, 'w', zipfile.ZIP_DEFLATED) as z:
|
||||
for name, data in all_files.items():
|
||||
z.writestr(name, data)
|
||||
wrote = True
|
||||
|
||||
if not wrote:
|
||||
# Циклов в шаблоне не было — возвращаем исходный файл,
|
||||
# пустой временный удаляем (иначе python-docx упадёт с Package not found)
|
||||
try:
|
||||
os.unlink(tmp.name)
|
||||
except Exception:
|
||||
pass
|
||||
return docx_path
|
||||
|
||||
return tmp.name
|
||||
|
||||
|
||||
Reference in New Issue
Block a user