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