-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathgenerate.py
39 lines (31 loc) · 1.44 KB
/
generate.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import argparse
import json
import os
import sys
from docxtpl import DocxTemplate
ENV_VARS_PREFIX = 'CIZI_PROBLEM'
DEFAULT_TEMPLATE = 'zadost_o_uplatneni_opatreni_proti_necinnosti_spravniho_organu.docx'
DEFAULT_RESULT_FILE = 'autogenerated.docx'
def generate_doc(template, context, result_file):
"""Generates a docx document and saves as a result_file"""
# do the actual generation
doc = DocxTemplate(template)
doc.render(context)
doc.save(result_file)
def main(args=sys.argv):
parser = argparse.ArgumentParser()
parser.add_argument('--result-file', default=DEFAULT_RESULT_FILE, help='File where result will be saved')
parser.add_argument('template', help='Path to a docx template file to use')
parser.add_argument('--context-file', help='Path to a context vars file to use for auto generation. In the absence env vars with certain prefix will be used')
parser.add_argument('--env-vars-prefix', help='Prefix of the env vars to use as context variables', default=ENV_VARS_PREFIX)
parsed = parser.parse_args()
if parsed.context_file:
with open(parsed.context_file) as f:
context = json.loads(f.read())
else:
context = {k: v for k, v in os.environ.items() if k.startswith(parsed.env_vars_prefix)}
# do the actual generation
generate_doc(parsed.template, context, parsed.result_file)
print("Saving result as {} ".format(parsed.result_file))
if __name__ == "__main__":
main()