diff --git a/atst/utils/docx.py b/atst/utils/docx.py new file mode 100644 index 00000000..86fa04a0 --- /dev/null +++ b/atst/utils/docx.py @@ -0,0 +1,45 @@ +import os +from io import BytesIO +from zipfile import ZipFile +from flask import render_template, current_app as app + + +class Docx: + DOCUMENT_FILE = "word/document.xml" + + @classmethod + def _template_path(cls, docx_file): + return os.path.join(app.root_path, "..", "templates", docx_file) + + @classmethod + def _template(cls, docx_file): + return ZipFile(Docx._template_path(docx_file), mode="r") + + @classmethod + def _write(cls, docx_template, docx_file, document): + with docx_template as template: + for item in template.infolist(): + if item.filename != Docx.DOCUMENT_FILE: + content = template.read(item.filename).decode() + else: + content = document + + docx_file.writestr(item, content) + + return docx_file + + @classmethod + def render( + cls, + doc_template="docx/document.xml", + file_template="docx/template.docx", + **args, + ): + document = render_template(doc_template, **args) + byte_str = BytesIO() + docx_file = ZipFile(byte_str, mode="w") + docx_template = Docx._template(file_template) + Docx._write(docx_template, docx_file, document) + docx_file.close() + byte_str.seek(0) + return byte_str.read() diff --git a/templates/docx/document.xml b/templates/docx/document.xml new file mode 100644 index 00000000..810064ad --- /dev/null +++ b/templates/docx/document.xml @@ -0,0 +1,12 @@ + + + + {% for key,val in data.items() %} + + + {{ key }}: {{ val }} + + + {% endfor %} + + diff --git a/templates/docx/template.docx b/templates/docx/template.docx new file mode 100644 index 00000000..7d4e3042 Binary files /dev/null and b/templates/docx/template.docx differ diff --git a/tests/utils/test_docx.py b/tests/utils/test_docx.py new file mode 100644 index 00000000..6d3064e0 --- /dev/null +++ b/tests/utils/test_docx.py @@ -0,0 +1,12 @@ +from io import BytesIO +from zipfile import ZipFile + +from atst.utils.docx import Docx + + +def test_render_docx(): + data = {"droid_class": "R2"} + docx_file = Docx.render(data=data) + zip_ = ZipFile(BytesIO(docx_file), mode="r") + document = zip_.read(Docx.DOCUMENT_FILE) + assert b"droid_class: R2" in document