mirror of
https://github.com/EDeev/mobiles_dataset.git
synced 2026-10-07 20:49:44 +03:00
Подключение к БД — из переменных окружения DB_*, лишние импорты убраны
- database.py, однофайловая копия для exe и импорт датасета читают DB_HOST, DB_PORT, DB_NAME, DB_USER, DB_PASSWORD; прежние значения остались значениями по умолчанию; - импорт находит датасет в корне репозитория независимо от текущей папки (или берёт путь первым аргументом); - 20 неиспользуемых импортов и переопределений после склейки файлов (ruff).
This commit is contained in:
parent
acc9e6b207
commit
20a36a7d1c
3 changed files with 32 additions and 19 deletions
10
database.py
10
database.py
|
|
@ -1,4 +1,5 @@
|
||||||
# db/database.py
|
# db/database.py
|
||||||
|
import os
|
||||||
import psycopg2
|
import psycopg2
|
||||||
from psycopg2.extras import RealDictCursor
|
from psycopg2.extras import RealDictCursor
|
||||||
from typing import List, Dict, Any, Optional
|
from typing import List, Dict, Any, Optional
|
||||||
|
|
@ -20,8 +21,13 @@ class Database:
|
||||||
cls._instance = super().__new__(cls)
|
cls._instance = super().__new__(cls)
|
||||||
return cls._instance
|
return cls._instance
|
||||||
|
|
||||||
def __init__(self, host='localhost', port=5432, database='mobile_devices_db',
|
def __init__(self, host=None, port=None, database=None, user=None, password=None):
|
||||||
user='admin', password='password'):
|
# Параметры подключения: аргументы, затем переменные окружения DB_*, затем значения для локальной разработки
|
||||||
|
host = host or os.environ.get('DB_HOST', 'localhost')
|
||||||
|
port = port or int(os.environ.get('DB_PORT', '5432'))
|
||||||
|
database = database or os.environ.get('DB_NAME', 'mobile_devices_db')
|
||||||
|
user = user or os.environ.get('DB_USER', 'admin')
|
||||||
|
password = password or os.environ.get('DB_PASSWORD', 'password')
|
||||||
if not hasattr(self, 'initialized'):
|
if not hasattr(self, 'initialized'):
|
||||||
self.connection_params = {
|
self.connection_params = {
|
||||||
'host': host,
|
'host': host,
|
||||||
|
|
|
||||||
|
|
@ -5,24 +5,21 @@ from PyQt6.QtWidgets import QApplication
|
||||||
from PyQt6.QtCore import Qt
|
from PyQt6.QtCore import Qt
|
||||||
|
|
||||||
# ui/main_window.py
|
# ui/main_window.py
|
||||||
import sys
|
|
||||||
from PyQt6.QtWidgets import (
|
from PyQt6.QtWidgets import (
|
||||||
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
|
QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
|
||||||
QTableWidget, QTableWidgetItem, QPushButton, QTabWidget,
|
QTableWidget, QTableWidgetItem, QPushButton, QTabWidget,
|
||||||
QLabel, QLineEdit, QComboBox, QSpinBox, QMessageBox,
|
QLabel, QLineEdit, QComboBox, QSpinBox, QMessageBox,
|
||||||
QDialog, QFormLayout, QDialogButtonBox, QHeaderView,
|
QDialog, QFormLayout, QDialogButtonBox, QHeaderView,
|
||||||
QToolBar, QStatusBar, QGroupBox, QTextEdit, QInputDialog
|
QToolBar, QStatusBar, QGroupBox, QTextEdit, QInputDialog
|
||||||
)
|
)
|
||||||
from PyQt6.QtCore import Qt, QTimer, pyqtSignal
|
from PyQt6.QtGui import QAction, QFont
|
||||||
from PyQt6.QtGui import QAction, QIcon, QFont
|
|
||||||
from typing import Optional, Dict, Any
|
from typing import Optional, Dict, Any
|
||||||
import logging
|
|
||||||
|
|
||||||
# db/database.py
|
# db/database.py
|
||||||
|
import os
|
||||||
import psycopg2
|
import psycopg2
|
||||||
from psycopg2.extras import RealDictCursor
|
from psycopg2.extras import RealDictCursor
|
||||||
from typing import List, Dict, Any, Optional
|
from typing import List
|
||||||
import logging
|
|
||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
@ -48,8 +45,13 @@ class Database:
|
||||||
cls._instance = super().__new__(cls)
|
cls._instance = super().__new__(cls)
|
||||||
return cls._instance
|
return cls._instance
|
||||||
|
|
||||||
def __init__(self, host='localhost', port=5432, database='mobile_devices_db',
|
def __init__(self, host=None, port=None, database=None, user=None, password=None):
|
||||||
user='admin', password='password'):
|
# Параметры подключения: аргументы, затем переменные окружения DB_*, затем значения для локальной разработки
|
||||||
|
host = host or os.environ.get('DB_HOST', 'localhost')
|
||||||
|
port = port or int(os.environ.get('DB_PORT', '5432'))
|
||||||
|
database = database or os.environ.get('DB_NAME', 'mobile_devices_db')
|
||||||
|
user = user or os.environ.get('DB_USER', 'admin')
|
||||||
|
password = password or os.environ.get('DB_PASSWORD', 'password')
|
||||||
if not hasattr(self, 'initialized'):
|
if not hasattr(self, 'initialized'):
|
||||||
self.connection_params = {
|
self.connection_params = {
|
||||||
'host': host,
|
'host': host,
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,9 @@
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
import psycopg2
|
import psycopg2
|
||||||
from psycopg2.extras import execute_values
|
|
||||||
import re
|
import re
|
||||||
from typing import Optional, Dict, Tuple
|
from typing import Optional, Dict
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
# Настройка логирования
|
# Настройка логирования
|
||||||
|
|
@ -245,12 +246,13 @@ class MobileDataImporter:
|
||||||
# Использование скрипта
|
# Использование скрипта
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
# Конфигурация подключения к БД
|
# Конфигурация подключения к БД
|
||||||
|
# Параметры подключения — из переменных окружения DB_* (по умолчанию — локальная разработка)
|
||||||
db_config = {
|
db_config = {
|
||||||
'host': 'localhost',
|
'host': os.environ.get('DB_HOST', 'localhost'),
|
||||||
'port': 5432,
|
'port': int(os.environ.get('DB_PORT', '5432')),
|
||||||
'database': 'mobile_devices_db',
|
'database': os.environ.get('DB_NAME', 'mobile_devices_db'),
|
||||||
'user': 'admin',
|
'user': os.environ.get('DB_USER', 'admin'),
|
||||||
'password': 'password' # Замените на ваш пароль
|
'password': os.environ.get('DB_PASSWORD', 'password'),
|
||||||
}
|
}
|
||||||
|
|
||||||
# Создаем импортер и выполняем импорт
|
# Создаем импортер и выполняем импорт
|
||||||
|
|
@ -258,6 +260,9 @@ if __name__ == "__main__":
|
||||||
|
|
||||||
try:
|
try:
|
||||||
importer.connect()
|
importer.connect()
|
||||||
importer.import_data('Mobiles Dataset 2025.csv') # Укажите путь к вашему файлу
|
# Датасет лежит в корне репозитория; другой файл можно передать первым аргументом
|
||||||
|
csv_path = sys.argv[1] if len(sys.argv) > 1 else os.path.join(
|
||||||
|
os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'Mobiles Dataset 2025.csv')
|
||||||
|
importer.import_data(csv_path)
|
||||||
finally:
|
finally:
|
||||||
importer.disconnect()
|
importer.disconnect()
|
||||||
Loading…
Add table
Reference in a new issue