Changed code to be python < 3.6 compatible

This commit is contained in:
Eric Lapouyade 2021-10-01 12:11:43 +02:00
parent b0a5de05aa
commit 541d5ce7cb
2 changed files with 34 additions and 32 deletions

View File

@ -1,6 +1,6 @@
import argparse import argparse
import json import json
from pathlib import Path import os
from .template import DocxTemplate, TemplateError from .template import DocxTemplate, TemplateError
@ -11,9 +11,9 @@ OVERWRITE_ARG = 'overwrite'
QUIET_ARG = 'quiet' QUIET_ARG = 'quiet'
def make_arg_parser() -> argparse.ArgumentParser: def make_arg_parser():
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
usage=f'python -m docxtpl [-h] [-o] [-q] {TEMPLATE_ARG} {JSON_ARG} {OUTPUT_ARG}', usage='python -m docxtpl [-h] [-o] [-q] {} {} {}'.format(TEMPLATE_ARG, JSON_ARG, OUTPUT_ARG),
description='Make docx file from existing template docx and json data.') description='Make docx file from existing template docx and json data.')
parser.add_argument(TEMPLATE_ARG, parser.add_argument(TEMPLATE_ARG,
type=str, type=str,
@ -33,7 +33,7 @@ def make_arg_parser() -> argparse.ArgumentParser:
return parser return parser
def get_args(parser: argparse.ArgumentParser) -> dict: def get_args(parser):
try: try:
parsed_args = vars(parser.parse_args()) parsed_args = vars(parser.parse_args())
return parsed_args return parsed_args
@ -43,15 +43,15 @@ def get_args(parser: argparse.ArgumentParser) -> dict:
if e.code == 0: if e.code == 0:
raise SystemExit from e raise SystemExit from e
else: else:
raise RuntimeError(f'Correct usage is:\n{parser.usage}') from e raise RuntimeError('Correct usage is:\n{parser.usage}'.format(parser=parser)) from e
def is_argument_valid(arg_name: str, arg_value: str, overwrite: bool) -> bool: def is_argument_valid(arg_name, arg_value, overwrite):
# Basic checks for the arguments # Basic checks for the arguments
if arg_name == TEMPLATE_ARG: if arg_name == TEMPLATE_ARG:
return Path(arg_value).is_file() and arg_value.endswith('.docx') return os.path.isfile(arg_value) and arg_value.endswith('.docx')
elif arg_name == JSON_ARG: elif arg_name == JSON_ARG:
return Path(arg_value).is_file() and arg_value.endswith('.json') return os.path.isfile(arg_value) and arg_value.endswith('.json')
elif arg_name == OUTPUT_ARG: elif arg_name == OUTPUT_ARG:
return arg_value.endswith('.docx') and check_exists_ask_overwrite( return arg_value.endswith('.docx') and check_exists_ask_overwrite(
arg_value, overwrite) arg_value, overwrite)
@ -59,23 +59,23 @@ def is_argument_valid(arg_name: str, arg_value: str, overwrite: bool) -> bool:
return arg_value in [True, False] return arg_value in [True, False]
def check_exists_ask_overwrite(arg_value: str, overwrite: bool) -> bool: def check_exists_ask_overwrite(arg_value, overwrite):
# If output file does not exist or command was run with overwrite option, # If output file does not exist or command was run with overwrite option,
# returns True, else asks for overwrite confirmation. If overwrite is # returns True, else asks for overwrite confirmation. If overwrite is
# confirmed returns True, else raises FileExistsError. # confirmed returns True, else raises FileExistsError.
if Path(arg_value).exists() and not overwrite: if os.path.exists(arg_value) and not overwrite:
try: try:
if input(f'File {arg_value} already exists, would you like to overwrite the existing file? (y/n)').lower() == 'y': if input('File %s already exists, would you like to overwrite the existing file? (y/n)' % arg_value).lower() == 'y':
return True return True
else: else:
raise FileExistsError raise FileExistsError
except FileExistsError as e: except FileExistsError as e:
raise RuntimeError(f'File {arg_value} already exists, please choose a different name.') from e raise RuntimeError('File %s already exists, please choose a different name.' % arg_value) from e
else: else:
return True return True
def validate_all_args(parsed_args: dict) -> None: def validate_all_args(parsed_args):
overwrite = parsed_args[OVERWRITE_ARG] overwrite = parsed_args[OVERWRITE_ARG]
# Raises AssertionError if any of the arguments is not validated # Raises AssertionError if any of the arguments is not validated
try: try:
@ -84,28 +84,32 @@ def validate_all_args(parsed_args: dict) -> None:
raise AssertionError raise AssertionError
except AssertionError as e: except AssertionError as e:
raise RuntimeError( raise RuntimeError(
f'The specified {arg_name} "{arg_value}" is not valid.') from e 'The specified {arg_name} "{arg_value}" is not valid.'.format(
arg_name=arg_name, arg_value=arg_value
)) from e
def get_json_data(json_path: Path) -> dict: def get_json_data(json_path):
with open(json_path) as file: with open(json_path) as file:
try: try:
json_data = json.load(file) json_data = json.load(file)
return json_data return json_data
except json.JSONDecodeError as e: except json.JSONDecodeError as e:
print( print(
f'There was an error on line {e.lineno}, column {e.colno} while trying to parse file {json_path}') 'There was an error on line {e.lineno}, column {e.colno} while trying to parse file {json_path}'.format(
e=e, json_path=json_path
))
raise RuntimeError('Failed to get json data.') from e raise RuntimeError('Failed to get json data.') from e
def make_docxtemplate(template_path: Path) -> DocxTemplate: def make_docxtemplate(template_path):
try: try:
return DocxTemplate(template_path) return DocxTemplate(template_path)
except TemplateError as e: except TemplateError as e:
raise RuntimeError('Could not create docx template.') from e raise RuntimeError('Could not create docx template.') from e
def render_docx(doc: DocxTemplate, json_data: dict) -> DocxTemplate: def render_docx(doc, json_data):
try: try:
doc.render(json_data) doc.render(json_data)
return doc return doc
@ -118,13 +122,13 @@ def save_file(doc: DocxTemplate, parsed_args: dict) -> None:
output_path = parsed_args[OUTPUT_ARG] output_path = parsed_args[OUTPUT_ARG]
doc.save(output_path) doc.save(output_path)
if not parsed_args[QUIET_ARG]: if not parsed_args[QUIET_ARG]:
print(f'Document successfully generated and saved at {output_path}') print('Document successfully generated and saved at {output_path}'.format(output_path=output_path))
except PermissionError as e: except PermissionError as e:
print(f'{e.strerror}. Could not save file {e.filename}.') print('{e.strerror}. Could not save file {e.filename}.'.foramt(e=e))
raise RuntimeError('Failed to save file.') from e raise RuntimeError('Failed to save file.') from e
def main() -> None: def main():
parser = make_arg_parser() parser = make_arg_parser()
# Everything is in a try-except block that cacthes a RuntimeError that is # Everything is in a try-except block that cacthes a RuntimeError that is
# raised if any of the individual functions called cause an error # raised if any of the individual functions called cause an error
@ -132,8 +136,8 @@ def main() -> None:
parsed_args = get_args(parser) parsed_args = get_args(parser)
try: try:
validate_all_args(parsed_args) validate_all_args(parsed_args)
json_data = get_json_data(Path(parsed_args[JSON_ARG]).resolve()) json_data = get_json_data(os.path.abspath(parsed_args[JSON_ARG]))
doc = make_docxtemplate(Path(parsed_args[TEMPLATE_ARG]).resolve()) doc = make_docxtemplate(os.path.abspath(parsed_args[TEMPLATE_ARG]))
doc = render_docx(doc, json_data) doc = render_docx(doc, json_data)
save_file(doc, parsed_args) save_file(doc, parsed_args)
except RuntimeError as e: except RuntimeError as e:

View File

@ -1,5 +1,4 @@
import os import os
from pathlib import Path
TEMPLATE_PATH = 'templates/module_execute_tpl.docx' TEMPLATE_PATH = 'templates/module_execute_tpl.docx'
JSON_PATH = 'templates/module_execute.json' JSON_PATH = 'templates/module_execute.json'
@ -8,14 +7,13 @@ OVERWRITE = '-o'
QUIET = '-q' QUIET = '-q'
output_path = Path(OUTPUT_FILENAME) if os.path.exists(OUTPUT_FILENAME):
if output_path.exists(): os.unlink(OUTPUT_FILENAME)
output_path.unlink()
os.chdir(Path(__file__).parent) os.chdir(os.path.dirname(__file__))
cmd = f'python -m docxtpl {TEMPLATE_PATH} {JSON_PATH} {OUTPUT_FILENAME} {OVERWRITE} {QUIET}' cmd = 'python -m docxtpl %s %s %s %s %s' % (TEMPLATE_PATH, JSON_PATH, OUTPUT_FILENAME, OVERWRITE, QUIET)
print(f'Executing "{cmd}" ...') print('Executing "%s" ...' % cmd)
os.system(cmd) os.system(cmd)
if output_path.exists(): if os.path.exists(OUTPUT_FILENAME):
print(f' --> File {output_path.resolve()} has been generated.') print(f' --> File %s has been generated.' % OUTPUT_FILENAME)