Spaces:
Sleeping
Sleeping
| from flask import Flask, request, jsonify, render_template | |
| import mysql.connector | |
| import os | |
| import time | |
| app = Flask(__name__, template_folder='/templates', static_folder='/static') | |
| # Параметри підключення до віддаленої бази даних | |
| DB_CONFIG = { | |
| "host": "mysql-emploees-zabolotniua-5b91.c.aivencloud.com", | |
| "port": 12374, | |
| "user": "avnadmin", | |
| "password": "AVNS_rccbF_so2YPvPk3zg0z" | |
| # Без SSL налаштувань | |
| } | |
| def get_db_connection(database=None): | |
| try: | |
| config = DB_CONFIG.copy() | |
| if database: | |
| config["database"] = database | |
| return mysql.connector.connect(**config) | |
| except Exception as e: | |
| print(f"Error connecting to MySQL: {e}") | |
| raise e | |
| def index(): | |
| # Перевіряємо статус MySQL | |
| status = {"status": "offline", "version": "Unknown"} | |
| try: | |
| conn = get_db_connection() | |
| cursor = conn.cursor() | |
| cursor.execute("SELECT VERSION()") | |
| version = cursor.fetchone()[0] | |
| status = {"status": "online", "version": version} | |
| # Отримуємо списки баз даних | |
| cursor.execute("SHOW DATABASES") | |
| databases = [db[0] for db in cursor.fetchall()] | |
| cursor.close() | |
| conn.close() | |
| # Перевіряємо наявність бази даних employees | |
| employees_exists = "employees" in databases | |
| connection_info = { | |
| "host": DB_CONFIG["host"], | |
| "port": DB_CONFIG["port"], | |
| "user": DB_CONFIG["user"], | |
| "password": DB_CONFIG["password"], | |
| "ssl_mode": "REQUIRED" # Тільки для відображення | |
| } | |
| return render_template('index.html', | |
| status=status, | |
| databases=databases, | |
| tables=[], | |
| employees_exists=employees_exists, | |
| remote_connection=True, | |
| connection_info=connection_info) | |
| except Exception as e: | |
| print(f"Error: {e}") | |
| connection_info = { | |
| "host": DB_CONFIG["host"], | |
| "port": DB_CONFIG["port"], | |
| "user": DB_CONFIG["user"], | |
| "password": DB_CONFIG["password"], | |
| "ssl_mode": "REQUIRED" # Тільки для відображення | |
| } | |
| return render_template('index.html', | |
| status={"status": "offline", "error": str(e)}, | |
| databases=[], | |
| tables=[], | |
| employees_exists=False, | |
| remote_connection=True, | |
| connection_info=connection_info) | |
| def show_database(database): | |
| try: | |
| conn = get_db_connection(database) | |
| cursor = conn.cursor() | |
| # Отримуємо списки таблиць | |
| cursor.execute(f"SHOW TABLES FROM `{database}`") | |
| tables = [table[0] for table in cursor.fetchall()] | |
| # Закриваємо з'єднання і створюємо нове для кожної таблиці | |
| cursor.close() | |
| conn.close() | |
| # Отримуємо інформацію про таблиці | |
| table_info = [] | |
| for table in tables: | |
| try: | |
| conn = get_db_connection(database) | |
| cursor = conn.cursor() | |
| # Отримуємо кількість рядків | |
| cursor.execute(f"SELECT COUNT(*) FROM `{database}`.`{table}`") | |
| count = cursor.fetchone()[0] | |
| table_info.append({ | |
| 'name': table, | |
| 'count': count, | |
| 'size': 'N/A' # Розмір не можемо отримати з віддаленої бази | |
| }) | |
| cursor.close() | |
| conn.close() | |
| except Exception as e: | |
| print(f"Error getting info for table {table}: {e}") | |
| table_info.append({ | |
| 'name': table, | |
| 'count': 'Error', | |
| 'size': 'Error' | |
| }) | |
| return render_template('database.html', | |
| database=database, | |
| tables=table_info, | |
| remote_connection=True) | |
| except Exception as e: | |
| return render_template('error.html', error=str(e)) | |
| def show_table(database, table_name): | |
| try: | |
| conn = get_db_connection(database) | |
| cursor = conn.cursor(dictionary=True) | |
| # Отримуємо структуру таблиці | |
| cursor.execute(f"DESCRIBE `{table_name}`") | |
| columns = cursor.fetchall() | |
| # Отримуємо дані таблиці | |
| cursor.execute(f"SELECT * FROM `{table_name}` LIMIT 100") | |
| data = cursor.fetchall() | |
| # Отримуємо загальну кількість рядків у таблиці | |
| cursor.execute(f"SELECT COUNT(*) as count FROM `{table_name}`") | |
| total_count = cursor.fetchone()['count'] | |
| conn.close() | |
| return render_template('table.html', | |
| database=database, | |
| table_name=table_name, | |
| columns=columns, | |
| data=data, | |
| total_count=total_count, | |
| remote_connection=True) | |
| except Exception as e: | |
| return render_template('error.html', error=str(e)) | |
| def execute_query(): | |
| # Отримуємо дані з форми або JSON | |
| if request.content_type == 'application/json': | |
| data = request.json | |
| query = data.get('query', '') | |
| database = data.get('database', 'employees') | |
| else: | |
| query = request.form.get('query', '') | |
| database = request.form.get('database', 'employees') | |
| if not query: | |
| return jsonify({'error': 'Запит не може бути порожнім'}), 400 | |
| try: | |
| conn = get_db_connection(database) | |
| cursor = conn.cursor(dictionary=True) | |
| cursor.execute(query) | |
| if query.lower().strip().startswith('select'): | |
| result = cursor.fetchall() | |
| conn.close() | |
| return render_template('result.html', | |
| results=result, | |
| query=query, | |
| database=database, | |
| remote_connection=True) | |
| else: | |
| conn.commit() | |
| affected_rows = cursor.rowcount | |
| conn.close() | |
| return render_template('result.html', | |
| affected_rows=affected_rows, | |
| query=query, | |
| database=database, | |
| remote_connection=True) | |
| except Exception as e: | |
| error_msg = str(e) | |
| return render_template('result.html', | |
| error=error_msg, | |
| query=query, | |
| database=database, | |
| remote_connection=True) | |
| def employees_info(): | |
| try: | |
| conn = get_db_connection('employees') | |
| cursor = conn.cursor(dictionary=True) | |
| # Отримуємо інформацію про таблиці | |
| cursor.execute("SHOW TABLES FROM employees") | |
| tables_result = cursor.fetchall() | |
| tables = [] | |
| # Знаходимо ім'я стовпця з назвою таблиці | |
| table_column_name = list(tables_result[0].keys())[0] if tables_result else None | |
| if table_column_name: | |
| tables = [table[table_column_name] for table in tables_result] | |
| tables_info = [] | |
| for table in tables: | |
| cursor.execute(f"SELECT COUNT(*) as count FROM employees.{table}") | |
| count = cursor.fetchone()['count'] | |
| tables_info.append({ | |
| 'table_name': table, | |
| 'employee_count': count, | |
| 'total_size_mb': 'N/A' # Не можемо отримати розмір з віддаленої бази | |
| }) | |
| # Отримуємо загальну кількість співробітників | |
| cursor.execute("SELECT COUNT(*) as count FROM employees") | |
| total_employees = cursor.fetchone()['count'] | |
| # Отримуємо кількість департаментів | |
| cursor.execute("SELECT COUNT(*) as count FROM departments") | |
| total_departments = cursor.fetchone()['count'] | |
| # Отримуємо діапазон дат | |
| cursor.execute("SELECT MIN(hire_date) as min_date, MAX(hire_date) as max_date FROM employees") | |
| date_range = cursor.fetchone() | |
| # Отримуємо кількість чоловіків і жінок | |
| cursor.execute(""" | |
| SELECT | |
| gender, | |
| COUNT(*) as count, | |
| ROUND(COUNT(*) * 100.0 / (SELECT COUNT(*) FROM employees), 2) as percentage | |
| FROM | |
| employees | |
| GROUP BY | |
| gender | |
| """) | |
| gender_stats = cursor.fetchall() | |
| # Отримуємо топ департаментів за кількістю співробітників | |
| cursor.execute(""" | |
| SELECT | |
| d.dept_name, | |
| COUNT(de.emp_no) as employee_count | |
| FROM | |
| departments d | |
| JOIN | |
| dept_emp de ON d.dept_no = de.dept_no | |
| WHERE | |
| de.to_date = '9999-01-01' | |
| GROUP BY | |
| d.dept_name | |
| ORDER BY | |
| employee_count DESC | |
| LIMIT 5 | |
| """) | |
| top_departments = cursor.fetchall() | |
| conn.close() | |
| return render_template('employees.html', | |
| tables_info=tables_info, | |
| total_employees=total_employees, | |
| total_departments=total_departments, | |
| date_range=date_range, | |
| gender_stats=gender_stats, | |
| top_departments=top_departments, | |
| remote_connection=True) | |
| except Exception as e: | |
| return render_template('error.html', error=str(e)) | |
| if __name__ == '__main__': | |
| # Запуск веб-сервера | |
| app.run(host='0.0.0.0', port=7860) |