-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexecuting.py
113 lines (99 loc) · 3.97 KB
/
executing.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
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import xml.etree.ElementTree as ET
from uuid import uuid4
import datetime
import os
import xml.etree.ElementTree as ET
from uuid import uuid4
from xml.dom import minidom
import datetime
from parser_docx import Parser
import re
import logging
class Executing():
def __init__(self):
try:
os.mkdir("templates")
except:
pass
self.__create_template()
def __create_template(self):
with open("./templates/template.py", "w", encoding="utf-8") as file:
file.write("""import xml.etree.ElementTree as ET
from uuid import uuid4
from xml.dom import minidom
import datetime
from parser_docx import Parser
import re
import os
import logging
class Template():
def __init__(self, path):
self.name_template = "Пример работы шаблона"
'''
Создает основную часть документа
'''
self.path_to_source = path
self.parser = Parser() # парсер .docx файлов
self.parser.set_path(path) # выбираем файл
self.name = f"ON_EMCHD_{datetime.datetime.now().strftime('%Y%m%d')}"
self.uid = f"{uuid4()}"
attribute = {'xmlns:xsi': "http://www.w3.org/2001/XMLSchema-instance",
'xmlns:xsd': "http://www.w3.org/2001/XMLSchema",
'ВерсФорм': "EMCHD_1",
'ПрЭлФорм': "00000000",
'ИдФайл': f"{self.name}_{self.uid}",
'xmlns': "urn://x-artefacts/EMCHD_1",
}
self.root = ET.Element('Доверенность', attrib=attribute)
def save(self, path_folder):
rough_string = ET.tostring(self.root, 'utf-8')
reparsed = minidom.parseString(rough_string)
xml_text = reparsed.toprettyxml(indent=" ")
with open(f'{path_folder}{os.sep}{self.name}_{self.uid}.xml', "w", encoding="utf-8") as file:
file.write(xml_text)
return f'{path_folder}{os.sep}{self.name}_{self.uid}.xml'
def __from_string(self, text: str):
try:
xml_string = re.sub('>[\s\\n\\r]+<', '><', text)
return ET.fromstring(xml_string)
except Exception as ex:
print(f"Ошибка в XML:\\n{text}")
logging.exception(ex)
raise ex
def __add_attribute(self, path, property, value):
element = self.__find_element(path)
element.attrib.update({f"{property}": f"{value}"})
def __find_element(self, path):
return self.root.find(path)
def __get_patronymic(self, fio_parts):
if isinstance(fio_parts, list) == False:
fio_parts = f"{fio_parts}".split(" ")
patronymic = f' Отчество="{fio_parts[-1].upper()}"' if len(fio_parts) == 3 else ''
return patronymic
def __get_fio(self, fio):
fio_parts = fio.split(" ")
return f'Фамилия="{fio_parts[0].upper()}" Имя="{fio_parts[1].upper()}" {self.__get_patronymic(fio_parts)}'
def __get_passport_number(self, number):
numbers_only = number.replace(" ", "")
formatted = f"{numbers_only[:2]} {numbers_only[2:4]} {numbers_only[4:]}"
return formatted
def custom(self):
'''
данная часть модифицируется
:return:
'''
""")
def __read_file(self, path):
with open(path, "r", encoding="utf-8") as file: # Используем бинарный режим записи
return file.read()
def load_template(self, path_to_template, files, path_to_folder):
local_vars = {}
exec(self.__read_file(path_to_template), globals(), local_vars)
for path in files:
template = local_vars.get("Template")(path)
template.custom()
yield template.save(path_to_folder)
def get_template(self, path_to_template):
local_vars = {}
exec(self.__read_file(path_to_template), globals(), local_vars)
return local_vars