From 541d5ce7cbeaa0341ca66ba22b9d0cd319122c4e Mon Sep 17 00:00:00 2001 From: Eric Lapouyade Date: Fri, 1 Oct 2021 12:11:43 +0200 Subject: [PATCH] Changed code to be python < 3.6 compatible --- docxtpl/__main__.py | 50 ++++++++++++++++++++++------------------- tests/module_execute.py | 16 ++++++------- 2 files changed, 34 insertions(+), 32 deletions(-) diff --git a/docxtpl/__main__.py b/docxtpl/__main__.py index 1ad2b63..0cb838b 100644 --- a/docxtpl/__main__.py +++ b/docxtpl/__main__.py @@ -1,6 +1,6 @@ import argparse import json -from pathlib import Path +import os from .template import DocxTemplate, TemplateError @@ -11,9 +11,9 @@ OVERWRITE_ARG = 'overwrite' QUIET_ARG = 'quiet' -def make_arg_parser() -> argparse.ArgumentParser: +def make_arg_parser(): 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.') parser.add_argument(TEMPLATE_ARG, type=str, @@ -33,7 +33,7 @@ def make_arg_parser() -> argparse.ArgumentParser: return parser -def get_args(parser: argparse.ArgumentParser) -> dict: +def get_args(parser): try: parsed_args = vars(parser.parse_args()) return parsed_args @@ -43,15 +43,15 @@ def get_args(parser: argparse.ArgumentParser) -> dict: if e.code == 0: raise SystemExit from e 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 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: - 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: return arg_value.endswith('.docx') and check_exists_ask_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] -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, # returns True, else asks for overwrite confirmation. If overwrite is # confirmed returns True, else raises FileExistsError. - if Path(arg_value).exists() and not overwrite: + if os.path.exists(arg_value) and not overwrite: 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 else: raise FileExistsError 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: return True -def validate_all_args(parsed_args: dict) -> None: +def validate_all_args(parsed_args): overwrite = parsed_args[OVERWRITE_ARG] # Raises AssertionError if any of the arguments is not validated try: @@ -84,28 +84,32 @@ def validate_all_args(parsed_args: dict) -> None: raise AssertionError except AssertionError as e: 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: try: json_data = json.load(file) return json_data except json.JSONDecodeError as e: 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 -def make_docxtemplate(template_path: Path) -> DocxTemplate: +def make_docxtemplate(template_path): try: return DocxTemplate(template_path) except TemplateError as 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: doc.render(json_data) return doc @@ -118,13 +122,13 @@ def save_file(doc: DocxTemplate, parsed_args: dict) -> None: output_path = parsed_args[OUTPUT_ARG] doc.save(output_path) 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: - 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 -def main() -> None: +def main(): parser = make_arg_parser() # Everything is in a try-except block that cacthes a RuntimeError that is # raised if any of the individual functions called cause an error @@ -132,8 +136,8 @@ def main() -> None: parsed_args = get_args(parser) try: validate_all_args(parsed_args) - json_data = get_json_data(Path(parsed_args[JSON_ARG]).resolve()) - doc = make_docxtemplate(Path(parsed_args[TEMPLATE_ARG]).resolve()) + json_data = get_json_data(os.path.abspath(parsed_args[JSON_ARG])) + doc = make_docxtemplate(os.path.abspath(parsed_args[TEMPLATE_ARG])) doc = render_docx(doc, json_data) save_file(doc, parsed_args) except RuntimeError as e: diff --git a/tests/module_execute.py b/tests/module_execute.py index e78b944..c280600 100644 --- a/tests/module_execute.py +++ b/tests/module_execute.py @@ -1,5 +1,4 @@ import os -from pathlib import Path TEMPLATE_PATH = 'templates/module_execute_tpl.docx' JSON_PATH = 'templates/module_execute.json' @@ -8,14 +7,13 @@ OVERWRITE = '-o' QUIET = '-q' -output_path = Path(OUTPUT_FILENAME) -if output_path.exists(): - output_path.unlink() +if os.path.exists(OUTPUT_FILENAME): + os.unlink(OUTPUT_FILENAME) -os.chdir(Path(__file__).parent) -cmd = f'python -m docxtpl {TEMPLATE_PATH} {JSON_PATH} {OUTPUT_FILENAME} {OVERWRITE} {QUIET}' -print(f'Executing "{cmd}" ...') +os.chdir(os.path.dirname(__file__)) +cmd = 'python -m docxtpl %s %s %s %s %s' % (TEMPLATE_PATH, JSON_PATH, OUTPUT_FILENAME, OVERWRITE, QUIET) +print('Executing "%s" ...' % cmd) os.system(cmd) -if output_path.exists(): - print(f' --> File {output_path.resolve()} has been generated.') +if os.path.exists(OUTPUT_FILENAME): + print(f' --> File %s has been generated.' % OUTPUT_FILENAME)