-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplate_creator.py
More file actions
68 lines (60 loc) · 2.47 KB
/
template_creator.py
File metadata and controls
68 lines (60 loc) · 2.47 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
from jinja2 import Environment, FileSystemLoader
import os
class TemplateCreator:
def __init__(self, file_path):
"""
(str) -> TemplateCreator
Constructor of the class. Loads the template
and saves in a private variable the file path.
If the name of the file does not contain
the html extension, it is added.
"""
current_dir = os.path.dirname(os.path.abspath(__file__))
environment = Environment(
loader=FileSystemLoader(current_dir + '/templates')
)
self.__template = environment.get_template('template.html.jnj2')
if file_path.endswith(".html"):
self.__file_path = file_path
else:
self.__file_path = file_path + ".html"
def __write_to_file(self, html):
"""
(str) -> None
Writes the string taken as argument in the file path.
"""
try:
with open(self.__file_path, "w") as file:
file.write(html)
print("File successfully created.")
except IOError as e:
print("Something went wrong while generating the file.")
print("I/O error({0}): {1}".format(e.errno, e.strerror))
def __generate_html(self, accepted_answers, average_score,
average_answer_count, comments):
"""
(int, int, int, dict) -> str
Returns the html code generated by the template
after replacing all the variables
"""
return self.__template.render(
accepted_answers=accepted_answers,
average_score=average_score,
average_answer_count=average_answer_count,
comments=comments
)
def generate_html_file(self, calculated_statistics, comments):
"""
(list, dict) -> None
Generates the html code from the template and the variables passed
and creates an html file.
"""
html = self.__generate_html(calculated_statistics[0],
calculated_statistics[1],
calculated_statistics[2],
comments)
self.__write_to_file(html)
if __name__ == "__main__":
current_dir = os.path.dirname(os.path.abspath(__file__))
template_creator = TemplateCreator(current_dir + "file.html")
template_creator.generate_html_file([1, 2, 3], {1: 2, 2: 3, 3: 4})