Hello,
I’m developing an app that generates a report from user inputs and a .docx template using python-docxtpl. The idea is to keep both the code and the template in a repository on GitHub, so that the program can access the template.
My first version of the program works on localhost, however when I deploy it I get the following error:
File "/home/appuser/venv/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 565, in _run_script
exec(code, module.__dict__)
File "/app/autoeya_v3/4_Python_source_code/AutoEYA_UI.py", line 120, in <module>
main()
File "/app/autoeya_v3/4_Python_source_code/AutoEYA_UI.py", line 100, in main
document = fill_docx(st.session_state)
File "/app/autoeya_v3/4_Python_source_code/AutoEYA_docx.py", line 57, in fill_docx
doc.render(data)
File "/home/appuser/venv/lib/python3.9/site-packages/docxtpl/template.py", line 359, in render
self.render_init()
File "/home/appuser/venv/lib/python3.9/site-packages/docxtpl/template.py", line 52, in render_init
self.init_docx()
File "/home/appuser/venv/lib/python3.9/site-packages/docxtpl/template.py", line 48, in init_docx
self.docx = Document(self.template_file)
File "/home/appuser/venv/lib/python3.9/site-packages/docx/api.py", line 25, in Document
document_part = Package.open(docx).main_document_part
File "/home/appuser/venv/lib/python3.9/site-packages/docx/opc/package.py", line 128, in open
pkg_reader = PackageReader.from_file(pkg_file)
File "/home/appuser/venv/lib/python3.9/site-packages/docx/opc/pkgreader.py", line 32, in from_file
phys_reader = PhysPkgReader(pkg_file)
File "/home/appuser/venv/lib/python3.9/site-packages/docx/opc/phys_pkg.py", line 30, in __new__
raise PackageNotFoundError(
docx.opc.exceptions.PackageNotFoundError: Package not found at 'Report_template.docx'
According to my (small) experience, the problem lies in the fact that python-docxtpl is not able to find the document in the indicated filepath. However, this only happens in the deployed version of the application - and the position of the files is the same on my personal machine and in the GitHub repository.
I already tried passing the relative path, the absolute path and using file handling, but nothing worked so far. Here is the code snippet that gives me problems:
def fill_docx(session_state):
# Get the absolute path of the template
template_path = 'Report_template.docx'
template_fullpath = os.path.abspath(template_path)
template_file = open(template_fullpath, "rb")
template_fullpath.close()
doc = DocxTemplate(template_file)
data = {
# data to be inserted in the template
}
doc.render(data)
return doc
If anyone knows a way to fix this I would be very grateful.