Hi VIKTOR-team,
Iโd like to ask a question regarding downloading a word file. We have internally developed code to automatically build reports/factsheets/appendices from scratch using the docx package. I am struggling with how properly download this docx-file on the VIKTOR platform.
To start with, this is the relevant importing-part:
from docx import Document
from internal_arcadis_module import generate_factsheet
The method below sits in my controller class and is triggered with a DownloadButton:
def export_stix_factsheet_word(self, params, **kwargs):
stix_file_resources: List[FileResource] = params.tab_1.input_section.stix_files
(...)
arcadis_factsheet = generate_factsheet.factsheet_of_stix_dir(...)
# This returns a Document() from python docx package
file_arc_factsheet = arc_factsheet_to_viktor_file(arc_factsheet=arcadis_factsheet )
# This returns a File() from viktor.core package
now = datetime.datetime.now()
return DownloadResult(file_arc_factsheet,
f'factsheet_{params.tab_1.factsheet_selection.factsheet_name}_{now}.docx')
The method arc_factsheet_to_viktor_file is as follows and makes use of a temporary path to store the docx-file:
def arc_factsheet_to_viktor_file(arcadis_factsheet: Document) -> File:
temp_file = NamedTemporaryFile(suffix='.docx', delete=False,
mode='wb')
temp_file.close()
path_temp_file = Path(temp_file.name)
# save factsheet at path_temp_file
factsheet = arcadis_factsheet.save(path_temp_file)
# make a File-object, with factsheet contents from temp file
file = File.from_path(Path(path_temp_file))
os.remove(temp_file.name)
return file
The problem is when the temporary file is removed by os.remove(temp_file.name), the code gives an error (see below). It works when the line is commented, but I feel that is not what I want because the temporary file will sit in my local folder forever.
2022-07-11 13:27:07.701 INFO : Job (uid: 505) received - EntityType: MyEntityType - function: export_stix_factsheet_word
2022-07-11 13:27:10.558 ERROR : Exception is raised
Traceback (most recent call last):
File "viktor_connector\connector.pyx", line 400, in connector.Job.execute
File "viktor\core.pyx", line 1799, in viktor.core._handle_job
File "viktor\core.pyx", line 1783, in viktor.core._handle_job.non_view_result
File "viktor\result.pyx", line 133, in viktor.result.DownloadResult._serialize
File "viktor\core.pyx", line 899, in viktor.core.File.open_binary
File "viktor\core.pyx", line 706, in viktor.core._PathFileManager.create_binary_file
File "viktor\core.pyx", line 459, in viktor.core._BinaryPathFile.__init__
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\...\\AppData\\Local\\Temp\\tmpwk4sqf85.docx'
2022-07-11 13:27:37.796 INFO : Reloading app...
My question is how to properly save and download the file? Your help is very much appreciated.