Jaf*_*ker 3 python python-docx
我的任务是从模板生成DOCX文件,然后通过Flask提供该文件。我使用python-docx-templates,它只是python-docx的包装,允许使用jinja模板。
最后,他们建议使用StringIO仅将文件保存在内存中,因此我的代码如下所示:
def report_doc(user_id):
# Prepare the data...
from docxtpl import DocxTemplate
doc = DocxTemplate(app.root_path+'/templates/report.docx')
doc.render({
# Pass parameters
})
from io import StringIO
file_stream = StringIO()
doc.save(file_stream)
return send_file(file_stream, as_attachment=True, attachment_filename='report_'+user_id+'.docx')
Run Code Online (Sandbox Code Playgroud)
保存时会引发错误TypeError: string argument expected, got 'bytes'。谷歌搜索后,我找到了这个答案,说ZipFile期待BytesIO。但是,当我用BytesIO代替StringIO时,它仅返回一个空文件,因此它不会引发任何错误,但绝对不会保存该文件。
在这种情况下究竟能做什么?如果这里有什么完全不对的地方,那么总体上该如何做?
谢谢!
UPD:这是对save函数调用的完整跟踪的异常:
File "/ms/controllers.py", line 1306, in report_doc
doc.save(file_stream)
File "/.env/lib/python3.5/site-packages/docx/document.py", line 142, in save
self._part.save(path_or_stream)
File "/.env/lib/python3.5/site-packages/docx/parts/document.py", line 129, in save
self.package.save(path_or_stream)
File "/.env/lib/python3.5/site-packages/docx/opc/package.py", line 160, in save
PackageWriter.write(pkg_file, self.rels, self.parts)
File "/.env/lib/python3.5/site-packages/docx/opc/pkgwriter.py", line 33, in write
PackageWriter._write_content_types_stream(phys_writer, parts)
File "/.env/lib/python3.5/site-packages/docx/opc/pkgwriter.py", line 45, in _write_content_types_stream
phys_writer.write(CONTENT_TYPES_URI, cti.blob)
File "/.env/lib/python3.5/site-packages/docx/opc/phys_pkg.py", line 155, in write
self._zipf.writestr(pack_uri.membername, blob)
File "/usr/lib/python3.5/zipfile.py", line 1581, in writestr
self.fp.write(zinfo.FileHeader(zip64))
TypeError: string argument expected, got 'bytes'
Run Code Online (Sandbox Code Playgroud)
使用BytesIO实例是正确的,但是您需要在将文件指针传递给之前回退文件指针send_file:
在调用send_file()之前,请确保文件指针位于要发送的数据的开头。
所以这应该工作:
import io
from docxtpl import DocxTemplate
def report_doc(user_id):
# Prepare the data...
doc = DocxTemplate(app.root_path+'/templates/report.docx')
doc.render({
# Pass parameters
})
file_stream = io.BytesIO()
doc.save(file_stream)
file_stream.seek(0)
return send_file(file_stream, as_attachment=True, attachment_filename='report_'+user_id+'.docx')
Run Code Online (Sandbox Code Playgroud)
(在Firefox上进行测试,我发现浏览器即使指定了不同的文件名,也一直从缓存中检索文件,因此您可能需要在测试时清除浏览器的缓存,或者如果浏览器支持,请禁用开发工具中的缓存,或者调整Flask的缓存缓存控制设置)。