Commit 8626b0fa84047b6f27605e1332c46e9d88a8f5cb

Authored by Василь Свідрик
1 parent 60d652eec2

fix turm off component

Showing 5 changed files with 20 additions and 28 deletions Inline Diff

__pycache__/routes.cpython-310.pyc
No preview for this file type
No preview for this file type
k2/__pycache__/k2rout.cpython-310.pyc
No preview for this file type
1 import zipfile 1 import zipfile
2 from flask import Flask, Blueprint, jsonify, render_template, redirect, url_for, session, g 2 from flask import Flask, Blueprint, jsonify, render_template, redirect, url_for, session, g
3 import os 3 import os
4 import shutil 4 import shutil
5 from flask import request 5 from flask import request
6 from .k2cfg import k2 6 from .k2cfg import k2
7 from .k2comp import Component 7 from .k2comp import Component
8 from flask_migrate import Migrate 8 from flask_migrate import Migrate
9 import requests 9 import requests
10 import subprocess 10 import subprocess
11 from flask import current_app 11 from flask import current_app
12 import yaml 12 import yaml
13 from functools import wraps 13 from functools import wraps
14 import os 14 import os
15 import sys 15 import sys
16 16
17 # initialize db 17 # initialize db
18 #migrate = Migrate(app, db) 18 #migrate = Migrate(app, db)
19 19
20 components_bp = Blueprint('components', __name__, template_folder='templates') 20 components_bp = Blueprint('components', __name__, template_folder='templates')
21 config = yaml.safe_load(open("db/first-login.yml")) 21 config = yaml.safe_load(open("db/first-login.yml"))
22 22
23 23
24 db = k2.db 24 db = k2.db
25 25
26 26
27 def first_login_required(view_func): 27 def first_login_required(view_func):
28 @wraps(view_func) 28 @wraps(view_func)
29 def decorated_view(*args, **kwargs): 29 def decorated_view(*args, **kwargs):
30 if 'username' not in session: 30 if 'username' not in session:
31 return redirect(url_for('components.first_login')) 31 return redirect(url_for('components.first_login'))
32 return view_func(*args, **kwargs) 32 return view_func(*args, **kwargs)
33 return decorated_view 33 return decorated_view
34 34
35 def append_to_yaml_file(file_path, data): 35 #def append_to_yaml_file(file_path, data):
36 with open(file_path, 'r') as f: 36 # with open(file_path, 'r') as f:
37 existing_data = yaml.safe_load(f) or [] 37 # existing_data = yaml.safe_load(f) or []
38 #
39 # if not existing_data:
40 # start_id = 1
41 # else:
42 # start_id = max(item.get('id', 0) for item in existing_data) + 1
43 #
44 # for i, item in enumerate(data, start=start_id):
45 # item['id'] = i
46 # existing_data.append(item)
47 #
48 # with open(file_path, 'w') as f:
49 # yaml.dump(existing_data, f, default_flow_style=False)
38 50
39 if not existing_data:
40 start_id = 1
41 else:
42 start_id = max(item.get('id', 0) for item in existing_data) + 1
43 51
44 for i, item in enumerate(data, start=start_id):
45 item['id'] = i
46 existing_data.append(item)
47
48 with open(file_path, 'w') as f:
49 yaml.dump(existing_data, f, default_flow_style=False)
50
51
52 def remove_from_yaml_file(file_path, component_name): 52 def remove_from_yaml_file(file_path, component_name):
53 with open(file_path, 'r') as f: 53 with open(file_path, 'r') as f:
54 existing_data = yaml.safe_load(f) or [] 54 existing_data = yaml.safe_load(f) or []
55 55
56 updated_data = [item for item in existing_data if item.get('component_name') != component_name] 56 updated_data = [item for item in existing_data if item.get('component_name') != component_name]
57 57
58 with open(file_path, 'w') as f: 58 with open(file_path, 'w') as f:
59 yaml.dump(updated_data, f, default_flow_style=False) 59 yaml.dump(updated_data, f, default_flow_style=False)
60 60
61 @components_bp.route('/api/languages', methods=['GET']) 61 @components_bp.route('/api/languages', methods=['GET'])
62 def find_language(): 62 def find_language():
63 components = Component.query.all() 63 components = Component.query.all()
64 languages_paths = [] 64 languages_paths = []
65 # Додаємо головну директорію languages 65 # Додаємо головну директорію languages
66 languages_paths.append('languages') 66 languages_paths.append('languages')
67 # Знаходимо шляхи до директорій languages всередині папки components 67 # Знаходимо шляхи до директорій languages всередині папки components
68 for component in components: 68 for component in components:
69 component_languages_directory = 'components/' + component.name + '/' + component.name + '/languages' 69 component_languages_directory = 'components/' + component.name + '/' + component.name + '/languages'
70 languages_paths.append(component_languages_directory) 70 languages_paths.append(component_languages_directory)
71 result = ';'.join(languages_paths) 71 result = ';'.join(languages_paths)
72 print(result) 72 print(result)
73 return result 73 return result
74 74
75 @components_bp.route('/api/add-to-menu', methods=['GET']) 75 @components_bp.route('/api/add-to-menu', methods=['GET'])
76 def add_to_menu(): 76 def add_to_menu():
77 data = [] 77 data = []
78 components = Component.query.all() 78 components = Component.query.all()
79 components_names = [component.name for component in components] 79 components_names = [component.name for component in components]
80 for components_names in components_names: 80 for components_names in components_names:
81 response = requests.get(f"{k2.domain}{components_names}/menu-admin-items") 81 response = requests.get(f"{k2.domain}{components_names}/menu-admin-items")
82 print(response) 82 print(response)
83 if response.status_code == 200: 83 if response.status_code == 200:
84 data.append(response.json()[0]) 84 data.append(response.json()[0])
85 else: 85 else:
86 data 86 data
87 # add component_name key for menu items 87 # add component_name key for menu items
88 for item in data: 88 for item in data:
89 item['component_name'] = components_names 89 item['component_name'] = components_names
90 k2.menu = data 90 k2.menu = data
91 return k2.menu 91 return k2.menu
92 92
93 @components_bp.route('/home', methods=['GET', 'POST']) 93 @components_bp.route('/home', methods=['GET', 'POST'])
94 @first_login_required 94 @first_login_required
95 def home(): 95 def home():
96 return redirect('/dashboard') 96 return redirect('/dashboard')
97 97
98 @components_bp.route('/first-login', methods=['GET', 'POST']) 98 @components_bp.route('/first-login', methods=['GET', 'POST'])
99 def first_login(): 99 def first_login():
100 if request.method == "POST": 100 if request.method == "POST":
101 username = request.form.get("username") 101 username = request.form.get("username")
102 password = request.form.get("password") 102 password = request.form.get("password")
103 for user in config["users"]: 103 for user in config["users"]:
104 if user["username"] == username and user["password"] == password: 104 if user["username"] == username and user["password"] == password:
105 session['username'] = username # Збереження ім'я користувача в сесії 105 session['username'] = username # Збереження ім'я користувача в сесії
106 return redirect(url_for('components.dashboard')) 106 return redirect(url_for('components.dashboard'))
107 return "Невірне ім'я користувача або пароль." 107 return "Невірне ім'я користувача або пароль."
108 return render_template('first-login.html') 108 return render_template('first-login.html')
109 109
110 110
111 @components_bp.route('/change_language/<lang>') 111 @components_bp.route('/change_language/<lang>')
112 def change_language(lang): 112 def change_language(lang):
113 session['lang'] = lang 113 session['lang'] = lang
114 k2.current_language = lang 114 k2.current_language = lang
115 return redirect(url_for('components.dashboard')) 115 return redirect(url_for('components.dashboard'))
116 116
117 @components_bp.route('/dashboard') 117 @components_bp.route('/dashboard')
118 @first_login_required 118 @first_login_required
119 def dashboard(): 119 def dashboard():
120 # Компоненти доступні для встановлення 120 # Компоненти доступні для встановлення
121 try: 121 try:
122 # GET-запит до API 122 # GET-запит до API
123 response = requests.get(f'{k2.update_domain}api/components') 123 response = requests.get(f'{k2.update_domain}api/components')
124 json_data = response.json() 124 json_data = response.json()
125 # Перетворення JSON-об'єкту на масив 125 # Перетворення JSON-об'єкту на масив
126 component_server = [item for item in json_data] 126 component_server = [item for item in json_data]
127 except: 127 except:
128 component_server = None 128 component_server = None
129 129
130 # Встановлені компоненти 130 # Встановлені компоненти
131 components = Component.query.all() 131 components = Component.query.all()
132 components_names = [component.name for component in components] 132 components_names = [component.name for component in components]
133 # Отримання значення пошукового запиту з параметрів URL 133 # Отримання значення пошукового запиту з параметрів URL
134 search_query = request.args.get('search_query') 134 search_query = request.args.get('search_query')
135 #print(search_query) 135 #print(search_query)
136 filtered_components = [] 136 filtered_components = []
137 if search_query: 137 if search_query:
138 filtered_components = [component for component in component_server if 138 filtered_components = [component for component in component_server if
139 (search_query.lower() in component['name'].lower() if component['name'] else False) or 139 (search_query.lower() in component['name'].lower() if component['name'] else False) or
140 (search_query.lower() in component['description'].lower() if component[ 140 (search_query.lower() in component['description'].lower() if component[
141 'description'] else False)] 141 'description'] else False)]
142 else: 142 else:
143 filtered_components = component_server 143 filtered_components = component_server
144 current_language = k2.current_language 144 current_language = k2.current_language
145 145
146 return render_template('dashboard.html', components=components, 146 return render_template('dashboard.html', components=components,
147 components_names=components_names, component_server=filtered_components, 147 components_names=components_names, component_server=filtered_components,
148 search_query=search_query, language=k2.menu ) 148 search_query=search_query, language=k2.menu )
149 149
150 @components_bp.route('/show_components/<string:component_id>') 150 @components_bp.route('/show_components/<string:component_id>')
151 def show_components(component_id): 151 def show_components(component_id):
152 response = requests.get(f'{k2.update_domain}api/components') 152 response = requests.get(f'{k2.update_domain}api/components')
153 json_data = response.json() 153 json_data = response.json()
154 selected_component = next((component for component in json_data if component['id'] == component_id), None) 154 selected_component = next((component for component in json_data if component['id'] == component_id), None)
155 return render_template('component-info.html', selected_component=selected_component) 155 return render_template('component-info.html', selected_component=selected_component)
156 156
157 @components_bp.route('/install_components_git/<string:component_id>') 157 @components_bp.route('/install_components_git/<string:component_id>')
158 def install_components_git(component_id): 158 def install_components_git(component_id):
159 # Шлях до головної папки проекту 159 # Шлях до головної папки проекту
160 project_folder = 'components' 160 project_folder = 'components'
161 #component = Component.get_repository_by_id(component_id) 161 #component = Component.get_repository_by_id(component_id)
162 response = requests.get(f'{k2.update_domain}api/components') 162 response = requests.get(f'{k2.update_domain}api/components')
163 json_data = response.json() 163 json_data = response.json()
164 selected_component = next((component for component in json_data if component['id'] == component_id), None) 164 selected_component = next((component for component in json_data if component['id'] == component_id), None)
165 # Назва репозиторія 165 # Назва репозиторія
166 repository_name = selected_component['name'] 166 repository_name = selected_component['name']
167 # Шлях до папки репозиторія в межах проекту 167 # Шлях до папки репозиторія в межах проекту
168 repository_folder = os.path.join(project_folder, repository_name) 168 repository_folder = os.path.join(project_folder, repository_name)
169 # URL репозиторія 169 # URL репозиторія
170 170
171 git_repo_url = selected_component['git_link'] 171 git_repo_url = selected_component['git_link']
172 try: 172 try:
173 # Перевірка наявності папки репозиторія 173 # Перевірка наявності папки репозиторія
174 if not os.path.exists(repository_folder): 174 if not os.path.exists(repository_folder):
175 # Створення папки репозиторія 175 # Створення папки репозиторія
176 os.makedirs(repository_folder) 176 os.makedirs(repository_folder)
177 # Шлях до файлу __init__.py 177 # Шлях до файлу __init__.py
178 init_file = os.path.join(repository_folder, '__init__.py') 178 init_file = os.path.join(repository_folder, '__init__.py')
179 # Перевірка наявності файлу __init__.py 179 # Перевірка наявності файлу __init__.py
180 if not os.path.exists(init_file): 180 if not os.path.exists(init_file):
181 # Створення пустого файлу __init__.py 181 # Створення пустого файлу __init__.py
182 open(init_file, 'a').close() 182 open(init_file, 'a').close()
183 #підключення до приватного репозиторію 183 #підключення до приватного репозиторію
184 #os.environ['GITLAB_PRIVATE_TOKEN'] = '8xxTpxrKVDGoXD5ynjiW' 184 #os.environ['GITLAB_PRIVATE_TOKEN'] = '8xxTpxrKVDGoXD5ynjiW'
185 #git_repo_url_with_token = git_repo_url.replace('https://', 185 #git_repo_url_with_token = git_repo_url.replace('https://',
186 # f'https://oauth2:{os.environ["GITLAB_PRIVATE_TOKEN"]}@') 186 # f'https://oauth2:{os.environ["GITLAB_PRIVATE_TOKEN"]}@')
187 187
188 # Команда для встановлення з використанням git_repo_url і повного шляху до папки репозиторія 188 # Команда для встановлення з використанням git_repo_url і повного шляху до папки репозиторія
189 command = ['venv/Scripts/python.exe', '-m', 'pip', 'install', '--use-pep517', 'git+' + git_repo_url, '--target=' + repository_folder] 189 command = ['venv/Scripts/python.exe', '-m', 'pip', 'install', '--use-pep517', 'git+' + git_repo_url, '--target=' + repository_folder]
190 # Виконуємо команду встановлення 190 # Виконуємо команду встановлення
191 subprocess.check_call(command) 191 subprocess.check_call(command)
192 192
193 # Шлях до файлу, до якого потрібно додати код 193 # Шлях до файлу, до якого потрібно додати код
194 file_path = 'routes.py' 194 file_path = 'routes.py'
195 # Код, який потрібно додати 195 # Код, який потрібно додати
196 code = selected_component['dependencies'] 196 code = selected_component['dependencies']
197 # Відкриття файлу у режимі дозапису 197 # Відкриття файлу у режимі дозапису
198 with open(file_path, 'a') as file: 198 with open(file_path, 'a') as file:
199 # Запис нового коду у файл 199 # Запис нового коду у файл
200 file.write('\n') 200 file.write('\n')
201 file.write(code) 201 file.write(code)
202 file.write('\n') 202 file.write('\n')
203 component = Component.query.filter_by(name=selected_component['name']).first() 203 component = Component.query.filter_by(name=selected_component['name']).first()
204 if not component: 204 if not component:
205 new_component = Component( 205 new_component = Component(
206 name=selected_component['name'], 206 name=selected_component['name'],
207 description=selected_component['description'], 207 description=selected_component['description'],
208 version=selected_component['version'], 208 version=selected_component['version'],
209 git_link=selected_component['git_link'], 209 git_link=selected_component['git_link'],
210 dependencies=selected_component['dependencies'], 210 dependencies=selected_component['dependencies'],
211 installed=True 211 installed=True
212 ) 212 )
213 # Add the new component to the database 213 # Add the new component to the database
214 db.session.add(new_component) 214 db.session.add(new_component)
215 db.session.commit() 215 db.session.commit()
216 216
217 # Повертаємо повідомлення про успішне встановлення 217 # Повертаємо повідомлення про успішне встановлення
218 return f'Installed successfully <meta http-equiv="refresh" content="1;url=/dashboard" />' 218 return f'Installed successfully <meta http-equiv="refresh" content="1;url=/dashboard" />'
219 except subprocess.CalledProcessError as e: 219 except subprocess.CalledProcessError as e:
220 return 'Error installing : ' + str(e) 220 return 'Error installing : ' + str(e)
221 221
222 @components_bp.route('/install_components/<string:component_id>') 222 @components_bp.route('/install_components/<string:component_id>')
223 def install_component_from_archive(component_id): 223 def install_component_from_archive(component_id):
224 # Шлях до головної папки проекту 224 # Шлях до головної папки проекту
225 project_folder = 'components' 225 project_folder = 'components'
226 # Отримати відповідну компоненту зі списку компонент 226 # Отримати відповідну компоненту зі списку компонент
227 response = requests.get(f'{k2.update_domain}api/components') 227 response = requests.get(f'{k2.update_domain}api/components')
228 json_data = response.json() 228 json_data = response.json()
229 selected_component = next((component for component in json_data if component['id'] == component_id), None) 229 selected_component = next((component for component in json_data if component['id'] == component_id), None)
230 if selected_component is None: 230 if selected_component is None:
231 return 'Component not found' 231 return 'Component not found'
232 # Отримати посилання на архів компоненти та версію 232 # Отримати посилання на архів компоненти та версію
233 archive_url = selected_component['latest_component_data'] 233 archive_url = selected_component['latest_component_data']
234 version = selected_component['latest_version'] 234 version = selected_component['latest_version']
235 try: 235 try:
236 # Створити шлях до папки компоненти згідно назви та версії 236 # Створити шлях до папки компоненти згідно назви та версії
237 component_folder = os.path.join(project_folder) 237 component_folder = os.path.join(project_folder)
238 os.makedirs(component_folder, exist_ok=True) 238 os.makedirs(component_folder, exist_ok=True)
239 # Завантажити архів компоненти 239 # Завантажити архів компоненти
240 response = requests.get(archive_url, stream=True) 240 response = requests.get(archive_url, stream=True)
241 response.raise_for_status() 241 response.raise_for_status()
242 # Шлях до завантаженого архіву 242 # Шлях до завантаженого архіву
243 archive_path = os.path.join(component_folder, f"{selected_component['name']}.zip") 243 archive_path = os.path.join(component_folder, f"{selected_component['name']}.zip")
244 # Встановити залежності з файлу requirements.txt 244 # Встановити залежності з файлу requirements.txt
245 245
246 # Зберегти архів на диск 246 # Зберегти архів на диск
247 with open(archive_path, "wb") as file: 247 with open(archive_path, "wb") as file:
248 for chunk in response.iter_content(chunk_size=8192): 248 for chunk in response.iter_content(chunk_size=8192):
249 file.write(chunk) 249 file.write(chunk)
250 # Розпакувати архів 250 # Розпакувати архів
251 with zipfile.ZipFile(archive_path, "r") as zip_ref: 251 with zipfile.ZipFile(archive_path, "r") as zip_ref:
252 zip_ref.extractall(component_folder) 252 zip_ref.extractall(component_folder)
253 253
254 # Видалити архів 254 # Видалити архів
255 os.remove(archive_path) 255 os.remove(archive_path)
256 256
257 # Шлях до файлу, до якого потрібно додати код 257 # Шлях до файлу, до якого потрібно додати код
258 file_path = 'routes.py' 258 file_path = 'routes.py'
259 # Код, який потрібно додати 259 # Код, який потрібно додати
260 code = f'''from components.{selected_component['name']}.{selected_component['name']}.views import {selected_component['name']}\napp.register_blueprint({selected_component['name']}, url_prefix='/{selected_component['name']}')''' 260 code = f'''from components.{selected_component['name']}.{selected_component['name']}.views import {selected_component['name']}\napp.register_blueprint({selected_component['name']}, url_prefix='/{selected_component['name']}')'''
261 #selected_component['dependencies'] 261 #selected_component['dependencies']
262 262
263 # Відкриття файлу у режимі дозапису 263 # Відкриття файлу у режимі дозапису
264 with open(file_path, 'a') as file: 264 with open(file_path, 'a') as file:
265 # Запис нового коду у файл 265 # Запис нового коду у файл
266 file.write('\n') 266 file.write('\n')
267 file.write(code) 267 file.write(code)
268 file.write('\n') 268 file.write('\n')
269 269
270 #Update database with the installed component 270 #Update database with the installed component
271 component = Component.query.filter_by(name=selected_component['name']).first() 271 component = Component.query.filter_by(name=selected_component['name']).first()
272 if not component: 272 if not component:
273 component = Component( 273 component = Component(
274 name=selected_component['name'], 274 name=selected_component['name'],
275 description=selected_component['description'], 275 description=selected_component['description'],
276 version=version, 276 version=version,
277 git_link=selected_component['git_link'], 277 git_link=selected_component['git_link'],
278 dependencies=code, 278 dependencies=code,
279 installed=True 279 installed=True
280 ) 280 )
281 db.session.add(component) 281 db.session.add(component)
282 else: 282 else:
283 component.version = version 283 component.version = version
284 component.git_link = selected_component['git_link'] 284 component.git_link = selected_component['git_link']
285 component.dependencies = code 285 component.dependencies = code
286 component.installed = True 286 component.installed = True
287 287
288 db.session.commit() 288 db.session.commit()
289 289
290 #add language folders 290 #add language folders
291 k2.search_babel_translation_directories() 291 k2.search_babel_translation_directories()
292 return f'''Component installed successfully: {selected_component["name"]} v{version} {k2.babel_translation_directories}, 292 return f'''Component installed successfully: {selected_component["name"]} v{version} {k2.babel_translation_directories},
293 \n \n please wait installing requirments... 293 \n \n please wait installing requirments...
294 <meta http-equiv="refresh" content="0;url=/install-requirments/{selected_component["name"]}" />''' 294 <meta http-equiv="refresh" content="0;url=/install-requirments/{selected_component["name"]}" />'''
295 295
296 except Exception as e: 296 except Exception as e:
297 return f'Error installing component: {str(e)}' 297 return f'Error installing component: {str(e)}'
298 298
299 @components_bp.route('/install-requirments/<string:selected_component_name>', methods=['GET']) 299 @components_bp.route('/install-requirments/<string:selected_component_name>', methods=['GET'])
300 def install_requirments(selected_component_name): 300 def install_requirments(selected_component_name):
301 #menu items api 301 #menu items
302 response = requests.get(f"{k2.domain}{selected_component_name}/menu-items")
303 if response.status_code == 200:
304 data = response.json()
305
306 else:
307 data = []
308 # add component_name key for menu items
309 for item in data:
310 item['component_name'] = selected_component_name
311 file_path = 'components/menu.yml'
312 append_to_yaml_file(file_path, data)
313 get_admin_menu() 302 get_admin_menu()
314 303
315 #install requirements 304 #install requirements
316 requirements_file = os.path.join('components', selected_component_name, "requirements.txt") 305 requirements_file = os.path.join('components', selected_component_name, "requirements.txt")
317 if os.path.isfile(requirements_file): 306 if os.path.isfile(requirements_file):
318 pip_command = f"{k2.venv_bin_path}/python -m pip install -r {requirements_file}" 307 pip_command = f"{k2.venv_bin_path}/python -m pip install -r {requirements_file}"
319 subprocess.run(pip_command, shell=True, check=True) 308 subprocess.run(pip_command, shell=True, check=True)
320 return f'''Requirements installed successfully 309 return f'''Requirements installed successfully
321 \n \n please wait installing requirments components... 310 \n \n please wait installing requirments components...
322 <meta http-equiv="refresh" content="1;url=/install-requirments-components" />''' 311 <meta http-equiv="refresh" content="1;url=/install-requirments-components" />'''
323 312
324 @components_bp.route('/install-requirments-components') 313 @components_bp.route('/install-requirments-components')
325 def install_requirements_components(): 314 def install_requirements_components():
326 # Откриття файлу requirements_components.txt 315 # Откриття файлу requirements_components.txt
327 requirements_file = 'requirements_components.txt' 316 requirements_file = 'requirements_components.txt'
328 component_ids = None 317 component_ids = None
329 if os.path.isfile(requirements_file): 318 if os.path.isfile(requirements_file):
330 with open('requirements_components.txt', 'r') as file: 319 with open('requirements_components.txt', 'r') as file:
331 component_ids = file.read().splitlines() 320 component_ids = file.read().splitlines()
332 if component_ids: 321 if component_ids:
333 for component_id in component_ids: 322 for component_id in component_ids:
334 # Виклик роуту '/install_components/<string:component_name>' для кожної назви компоненти 323 # Виклик роуту '/install_components/<string:component_name>' для кожної назви компоненти
335 response = requests.get( 324 response = requests.get(
336 f'/install_components/{component_id}') 325 f'/install_components/{component_id}')
337 return f'Requirements components installed successfully <meta http-equiv="refresh" content="1;url=/dashboard" />' 326 return f'Requirements components installed successfully <meta http-equiv="refresh" content="1;url=/dashboard" />'
338 else: 327 else:
339 return f'<meta http-equiv="refresh" content="1;url=/dashboard" />' 328 return f'<meta http-equiv="refresh" content="1;url=/dashboard" />'
340 # Опрацювання відповіді (за потреби) 329 # Опрацювання відповіді (за потреби)
341 330
342 @components_bp.route('/remove_dependencies/<string:component_id>', methods=['GET']) 331 @components_bp.route('/remove_dependencies/<string:component_id>', methods=['GET'])
343 def remove_dependencies(component_id): 332 def remove_dependencies(component_id):
344 # Знаходимо компоненту за її ID 333 # Знаходимо компоненту за її ID
345 component = Component.query.get(component_id) 334 component = Component.query.get(component_id)
346 if not component: 335 if not component:
347 return 'Component not found <meta http-equiv="refresh" content="1;url=/dashboard" />' 336 return 'Component not found <meta http-equiv="refresh" content="1;url=/dashboard" />'
348 #remove menu items 337 #remove menu items
349 component_name = component.name 338 component_name = component.name
350 #file_path = "components/menu.yml" 339 #file_path = "components/menu.yml"
351 #remove_from_yaml_file(file_path, component_name) 340 #remove_from_yaml_file(file_path, component_name)
352 requests.get(f"{k2.domain}api/add-to-menu") 341 requests.get(f"{k2.domain}api/add-to-menu")
353 # remove routes 342 # remove routes
354 file_path = 'routes.py' 343 file_path = 'routes.py'
355 with open(file_path, 'r') as file: 344 with open(file_path, 'r') as file:
356 lines = file.readlines() 345 lines = file.readlines()
357 346
358 updated_lines = [line for line in lines if line.strip() not in component.dependencies] 347 updated_lines = [line for line in lines if line.strip() not in component.dependencies]
359 with open(file_path, 'w') as file: 348 with open(file_path, 'w') as file:
360 file.writelines(updated_lines) 349 file.writelines(updated_lines)
361 350
362 component.installed = False 351 component.installed = False
363 db.session.commit() 352 db.session.commit()
364 353
365 return 'Component successfully turn off <meta http-equiv="refresh" content="1;url=/dashboard" />' 354 return 'Component successfully turn off <meta http-equiv="refresh" content="1;url=/dashboard" />'
366 355
367 @components_bp.route('/add_dependencies/<string:component_id>', methods=['GET']) 356 @components_bp.route('/add_dependencies/<string:component_id>', methods=['GET'])
368 def add_dependencies(component_id): 357 def add_dependencies(component_id):
369 358
370 # Знаходимо компоненту за її ID 359 # Знаходимо компоненту за її ID
371 component = Component.query.get(component_id) 360 component = Component.query.get(component_id)
372 if not component: 361 if not component:
373 return 'Component not found <meta http-equiv="refresh" content="1;url=/dashboard" />' 362 return 'Component not found <meta http-equiv="refresh" content="1;url=/dashboard" />'
374 363
375 file_path = 'routes.py' 364 file_path = 'routes.py'
376 code = component.dependencies 365 code = component.dependencies
377 # Відкриття файлу у режимі дозапису 366 # Відкриття файлу у режимі дозапису
378 with open(file_path, 'a') as file: 367 with open(file_path, 'a') as file:
379 # Запис нового коду у файл 368 # Запис нового коду у файл
380 file.write(code) 369 file.write(code)
381 370
382 # Оновлюємо статус компоненти 371 # Оновлюємо статус компоненти
383 component.installed = True 372 component.installed = True
384 db.session.commit() 373 db.session.commit()
385 return 'Dependencies added successfully <meta http-equiv="refresh" content="1;url=/dashboard" />' 374 return 'Dependencies added successfully <meta http-equiv="refresh" content="1;url=/dashboard" />'
386 375
387 @components_bp.route('/remove-component/<string:component_id>') 376 @components_bp.route('/remove-component/<string:component_id>')
388 def remove_component(component_id): 377 def remove_component(component_id):
389 # Шлях до головної папки проекту 378 # Шлях до головної папки проекту
390 project_folder = 'components' 379 project_folder = 'components'
391 component = Component.query.get(component_id) 380 component = Component.query.get(component_id)
392 # Назва репозиторія 381 # Назва репозиторія
393 repository_name = component.name 382 repository_name = component.name
394 # Шлях до папки репозиторія в межах проекту 383 # Шлях до папки репозиторія в межах проекту
395 repository_folder = os.path.join(project_folder, repository_name) 384 repository_folder = os.path.join(project_folder, repository_name)
396 try: 385 try:
397 # Перевірка наявності папки репозиторія 386 # Перевірка наявності папки репозиторія
398 if os.path.exists(repository_folder): 387 if os.path.exists(repository_folder):
399 # Видалення папки репозиторія 388 # Видалення папки репозиторія
400 shutil.rmtree(repository_folder) 389 shutil.rmtree(repository_folder)
401 # Видаляємо компоненту з бази 390 # Видаляємо компоненту з бази
402 if component: 391 if component:
403 db.session.delete(component) 392 db.session.delete(component)
404 db.session.commit() 393 db.session.commit()
1 #app = Flask(__name__) 1 #app = Flask(__name__)
2 from main import app 2 from main import app
3 from k2.k2rout import components_bp 3 from k2.k2rout import components_bp
4 app.register_blueprint(components_bp) 4 app.register_blueprint(components_bp)
5 from components.k2test.k2test.views import k2test 5 from components.k2test.k2test.views import k2test
6 app.register_blueprint(k2test, url_prefix='/k2test') 6 app.register_blueprint(k2test, url_prefix='/k2test')
7 from components.grid.grid.views import grid 7 from components.grid.grid.views import grid
8 app.register_blueprint(grid, url_prefix='/grid') 8 app.register_blueprint(grid, url_prefix='/grid')
9 from components.vue.vue.views import vue2 9 from components.vue.vue.views import vue2
10 app.register_blueprint(vue2, url_prefix='/') 10 app.register_blueprint(vue2, url_prefix='/')
11
12 from components.adm.adm.views import adm
13 app.register_blueprint(adm, url_prefix='/adm')
14