Commit 44a25fe29a44f649539411ab5da27d9f79d3ba35

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

add components fron admin

Showing 5 changed files with 116 additions and 51 deletions Side-by-side 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 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, jsonify
3 3 import os
4 4 import shutil
5 5 from flask import request
6 6  
... ... @@ -15,12 +15,11 @@
15 15 import sys
16 16  
17 17 # initialize db
18   -#migrate = Migrate(app, db)
  18 +# migrate = Migrate(app, db)
19 19  
20 20 components_bp = Blueprint('components', __name__, template_folder='templates')
21 21 config = yaml.safe_load(open("db/first-login.yml"))
22 22  
23   -
24 23 db = k2.db
25 24  
26 25  
27 26  
... ... @@ -30,9 +29,11 @@
30 29 if 'username' not in session:
31 30 return redirect(url_for('components.first_login'))
32 31 return view_func(*args, **kwargs)
  32 +
33 33 return decorated_view
34 34  
35   -#def append_to_yaml_file(file_path, data):
  35 +
  36 +# def append_to_yaml_file(file_path, data):
36 37 # with open(file_path, 'r') as f:
37 38 # existing_data = yaml.safe_load(f) or []
38 39 #
... ... @@ -58,6 +59,7 @@
58 59 with open(file_path, 'w') as f:
59 60 yaml.dump(updated_data, f, default_flow_style=False)
60 61  
  62 +
61 63 @components_bp.route('/api/languages', methods=['GET'])
62 64 def find_language():
63 65 components = Component.query.all()
64 66  
... ... @@ -72,29 +74,13 @@
72 74 print(result)
73 75 return result
74 76  
75   -@components_bp.route('/api/add-to-menu', methods=['GET'])
76   -def add_to_menu():
77   - data = []
78   - components = Component.query.all()
79   - components_names = [component.name for component in components]
80   - for components_names in components_names:
81   - response = requests.get(f"{k2.domain}{components_names}/menu-admin-items")
82   - print(response)
83   - if response.status_code == 200:
84   - data.append(response.json()[0])
85   - else:
86   - data
87   - # add component_name key for menu items
88   - for item in data:
89   - item['component_name'] = components_names
90   - k2.menu = data
91   - return k2.menu
92 77  
93 78 @components_bp.route('/home', methods=['GET', 'POST'])
94 79 @first_login_required
95 80 def home():
96 81 return redirect('/dashboard')
97 82  
  83 +
98 84 @components_bp.route('/first-login', methods=['GET', 'POST'])
99 85 def first_login():
100 86 if request.method == "POST":
101 87  
... ... @@ -114,10 +100,11 @@
114 100 k2.current_language = lang
115 101 return redirect(url_for('components.dashboard'))
116 102  
  103 +
117 104 @components_bp.route('/dashboard')
118 105 @first_login_required
119 106 def dashboard():
120   - # Компоненти доступні для встановлення
  107 + # Компоненти доступні для встановлення
121 108 try:
122 109 # GET-запит до API
123 110 response = requests.get(f'{k2.update_domain}api/components')
... ... @@ -132,7 +119,7 @@
132 119 components_names = [component.name for component in components]
133 120 # Отримання значення пошукового запиту з параметрів URL
134 121 search_query = request.args.get('search_query')
135   - #print(search_query)
  122 + # print(search_query)
136 123 filtered_components = []
137 124 if search_query:
138 125 filtered_components = [component for component in component_server if
139 126  
... ... @@ -145,8 +132,9 @@
145 132  
146 133 return render_template('dashboard.html', components=components,
147 134 components_names=components_names, component_server=filtered_components,
148   - search_query=search_query, language=k2.menu )
  135 + search_query=search_query, language=k2.menu)
149 136  
  137 +
150 138 @components_bp.route('/show_components/<string:component_id>')
151 139 def show_components(component_id):
152 140 response = requests.get(f'{k2.update_domain}api/components')
153 141  
... ... @@ -154,11 +142,12 @@
154 142 selected_component = next((component for component in json_data if component['id'] == component_id), None)
155 143 return render_template('component-info.html', selected_component=selected_component)
156 144  
  145 +
157 146 @components_bp.route('/install_components_git/<string:component_id>')
158 147 def install_components_git(component_id):
159 148 # Шлях до головної папки проекту
160 149 project_folder = 'components'
161   - #component = Component.get_repository_by_id(component_id)
  150 + # component = Component.get_repository_by_id(component_id)
162 151 response = requests.get(f'{k2.update_domain}api/components')
163 152 json_data = response.json()
164 153 selected_component = next((component for component in json_data if component['id'] == component_id), None)
165 154  
... ... @@ -180,13 +169,14 @@
180 169 if not os.path.exists(init_file):
181 170 # Створення пустого файлу __init__.py
182 171 open(init_file, 'a').close()
183   - #підключення до приватного репозиторію
184   - #os.environ['GITLAB_PRIVATE_TOKEN'] = '8xxTpxrKVDGoXD5ynjiW'
185   - #git_repo_url_with_token = git_repo_url.replace('https://',
  172 + # підключення до приватного репозиторію
  173 + # os.environ['GITLAB_PRIVATE_TOKEN'] = '8xxTpxrKVDGoXD5ynjiW'
  174 + # git_repo_url_with_token = git_repo_url.replace('https://',
186 175 # f'https://oauth2:{os.environ["GITLAB_PRIVATE_TOKEN"]}@')
187 176  
188 177 # Команда для встановлення з використанням git_repo_url і повного шляху до папки репозиторія
189   - command = ['venv/Scripts/python.exe', '-m', 'pip', 'install', '--use-pep517', 'git+' + git_repo_url, '--target=' + repository_folder]
  178 + command = ['venv/Scripts/python.exe', '-m', 'pip', 'install', '--use-pep517', 'git+' + git_repo_url,
  179 + '--target=' + repository_folder]
190 180 # Виконуємо команду встановлення
191 181 subprocess.check_call(command)
192 182  
193 183  
... ... @@ -200,16 +190,16 @@
200 190 file.write('\n')
201 191 file.write(code)
202 192 file.write('\n')
203   - component = Component.query.filter_by(name=selected_component['name']).first()
  193 + component = Component.query.filter_by(name=selected_component['name']).first()
204 194 if not component:
205 195 new_component = Component(
206   - name=selected_component['name'],
207   - description=selected_component['description'],
208   - version=selected_component['version'],
209   - git_link=selected_component['git_link'],
210   - dependencies=selected_component['dependencies'],
211   - installed=True
212   - )
  196 + name=selected_component['name'],
  197 + description=selected_component['description'],
  198 + version=selected_component['version'],
  199 + git_link=selected_component['git_link'],
  200 + dependencies=selected_component['dependencies'],
  201 + installed=True
  202 + )
213 203 # Add the new component to the database
214 204 db.session.add(new_component)
215 205 db.session.commit()
... ... @@ -219,6 +209,7 @@
219 209 except subprocess.CalledProcessError as e:
220 210 return 'Error installing : ' + str(e)
221 211  
  212 +
222 213 @components_bp.route('/install_components/<string:component_id>')
223 214 def install_component_from_archive(component_id):
224 215 # Шлях до головної папки проекту
... ... @@ -258,7 +249,7 @@
258 249 file_path = 'routes.py'
259 250 # Код, який потрібно додати
260 251 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']
  252 + # selected_component['dependencies']
262 253  
263 254 # Відкриття файлу у режимі дозапису
264 255 with open(file_path, 'a') as file:
... ... @@ -267,7 +258,7 @@
267 258 file.write(code)
268 259 file.write('\n')
269 260  
270   - #Update database with the installed component
  261 + # Update database with the installed component
271 262 component = Component.query.filter_by(name=selected_component['name']).first()
272 263 if not component:
273 264 component = Component(
... ... @@ -287,7 +278,7 @@
287 278  
288 279 db.session.commit()
289 280  
290   - #add language folders
  281 + # add language folders
291 282 k2.search_babel_translation_directories()
292 283 return f'''Component installed successfully: {selected_component["name"]} v{version} {k2.babel_translation_directories},
293 284 \n \n please wait installing requirments...
294 285  
295 286  
... ... @@ -296,12 +287,13 @@
296 287 except Exception as e:
297 288 return f'Error installing component: {str(e)}'
298 289  
  290 +
299 291 @components_bp.route('/install-requirments/<string:selected_component_name>', methods=['GET'])
300 292 def install_requirments(selected_component_name):
301   - #menu items
  293 + # menu items
302 294 get_admin_menu()
303 295  
304   - #install requirements
  296 + # install requirements
305 297 requirements_file = os.path.join('components', selected_component_name, "requirements.txt")
306 298 if os.path.isfile(requirements_file):
307 299 pip_command = f"{k2.venv_bin_path}/python -m pip install -r {requirements_file}"
... ... @@ -310,6 +302,7 @@
310 302 \n \n please wait installing requirments components...
311 303 <meta http-equiv="refresh" content="1;url=/install-requirments-components" />'''
312 304  
  305 +
313 306 @components_bp.route('/install-requirments-components')
314 307 def install_requirements_components():
315 308 # Откриття файлу requirements_components.txt
316 309  
317 310  
... ... @@ -326,18 +319,19 @@
326 319 return f'Requirements components installed successfully <meta http-equiv="refresh" content="1;url=/dashboard" />'
327 320 else:
328 321 return f'<meta http-equiv="refresh" content="1;url=/dashboard" />'
329   - # Опрацювання відповіді (за потреби)
  322 + # Опрацювання відповіді (за потреби)
330 323  
  324 +
331 325 @components_bp.route('/remove_dependencies/<string:component_id>', methods=['GET'])
332 326 def remove_dependencies(component_id):
333 327 # Знаходимо компоненту за її ID
334 328 component = Component.query.get(component_id)
335 329 if not component:
336 330 return 'Component not found <meta http-equiv="refresh" content="1;url=/dashboard" />'
337   - #remove menu items
338   - component_name = component.name
339   - #file_path = "components/menu.yml"
340   - #remove_from_yaml_file(file_path, component_name)
  331 + # remove menu items
  332 + component_name = component.name
  333 + # file_path = "components/menu.yml"
  334 + # remove_from_yaml_file(file_path, component_name)
341 335 requests.get(f"{k2.domain}api/add-to-menu")
342 336 # remove routes
343 337 file_path = 'routes.py'
344 338  
... ... @@ -353,9 +347,9 @@
353 347  
354 348 return 'Component successfully turn off <meta http-equiv="refresh" content="1;url=/dashboard" />'
355 349  
  350 +
356 351 @components_bp.route('/add_dependencies/<string:component_id>', methods=['GET'])
357 352 def add_dependencies(component_id):
358   -
359 353 # Знаходимо компоненту за її ID
360 354 component = Component.query.get(component_id)
361 355 if not component:
... ... @@ -373,6 +367,7 @@
373 367 db.session.commit()
374 368 return 'Dependencies added successfully <meta http-equiv="refresh" content="1;url=/dashboard" />'
375 369  
  370 +
376 371 @components_bp.route('/remove-component/<string:component_id>')
377 372 def remove_component(component_id):
378 373 # Шлях до головної папки проекту
379 374  
... ... @@ -398,8 +393,80 @@
398 393 # Повертаємо повідомлення про помилку видалення
399 394 return 'Error removing component: ' + str(e)
400 395  
  396 +
  397 +
  398 +
  399 +@components_bp.route('/component/add')
  400 +def component_add():
  401 + # components for install
  402 + try:
  403 + # GET-requests to API
  404 + response = requests.get(f'{k2.update_domain}api/components')
  405 + json_data = response.json()
  406 + for item in json_data:
  407 + item['button'] = f"{k2.domain}/install_components/{item['id']}"
  408 +
  409 + except:
  410 + json_data = None
  411 + return jsonify(json_data)
  412 +
  413 +
  414 +@components_bp.route('/component/list')
  415 +def component_list():
  416 + # Встановлені компоненти
  417 + component_list = []
  418 + components = Component.query.all()
  419 + for component in components:
  420 + component_dict = {}
  421 + component_dict['name'] = component.name
  422 + component_dict['id'] = component.id
  423 + component_dict['description'] = component.description
  424 + component_dict['version'] = component.version
  425 + component_dict['button_off'] =f"{k2.domain}/remove_dependencies/{component.id}"
  426 + component_dict['button_on'] = f"{k2.domain}/add_dependencies/{component.id}"
  427 + component_dict['button_del'] = f"{k2.domain}/remove-component/{component.id}"
  428 + component_list.append(component_dict)
  429 + return jsonify(component_list)
  430 +
  431 +# menu
  432 +@components_bp.route('/api/add-to-menu', methods=['GET'])
  433 +def add_to_menu():
  434 + data = []
  435 + response = requests.get(f"{k2.domain}/menu-admin-items")
  436 + data.append(response.json()[0])
  437 + components = Component.query.all()
  438 + components_names = [component.name for component in components]
  439 + for components_names in components_names:
  440 + response = requests.get(f"{k2.domain}{components_names}/menu-admin-items")
  441 + print(response)
  442 + if response.status_code == 200:
  443 + data.append(response.json()[0])
  444 + else:
  445 + data
  446 + # add component_name key for menu items
  447 + for item in data:
  448 + item['component_name'] = components_names
  449 + k2.menu = data
  450 + return k2.menu
  451 +
  452 +
401 453 @components_bp.route('/api/main-menu/')
402 454 def get_admin_menu():
403 455 requests.get(f"{k2.domain}api/add-to-menu")
404 456 return k2.menu
  457 +
  458 +
  459 +@components_bp.route('/menu-admin-items')
  460 +def menu_items():
  461 + menu = [
  462 + {
  463 + "title": 'Add components',
  464 + "icon": {"icon": 'mdi-account-circle-outline'},
  465 + "children": [
  466 + {'title': 'Install components', 'to': 'component-add'},
  467 + {'title': 'Installed components', 'to': 'component-list'},
  468 +
  469 + ],
  470 + }]
  471 + return menu
... ... @@ -8,7 +8,4 @@
8 8 app.register_blueprint(grid, url_prefix='/grid')
9 9 from components.vue.vue.views import vue2
10 10 app.register_blueprint(vue2, url_prefix='/')
11   -
12   -from components.adm.adm.views import adm
13   -app.register_blueprint(adm, url_prefix='/adm')