create tables
This commit is contained in:
@@ -2,6 +2,7 @@ from autoLoader.config import FILESAPTH
|
|||||||
from autoLoader.loader import ConnectorSFTP
|
from autoLoader.loader import ConnectorSFTP
|
||||||
import datetime, os
|
import datetime, os
|
||||||
from autoLoader.database import Audio, get_db_session
|
from autoLoader.database import Audio, get_db_session
|
||||||
|
from sqlalchemy import inspect
|
||||||
|
|
||||||
local_path = os.path.join(os.getcwd(), FILESAPTH)
|
local_path = os.path.join(os.getcwd(), FILESAPTH)
|
||||||
|
|
||||||
@@ -15,7 +16,25 @@ class Loader():
|
|||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
def check_database(self):
|
||||||
|
"""Проверяет существование таблиц в БД"""
|
||||||
|
from autoLoader.database import engine
|
||||||
|
|
||||||
|
inspector = inspect(engine)
|
||||||
|
existing_tables = inspector.get_table_names()
|
||||||
|
|
||||||
|
if 'audio' not in existing_tables:
|
||||||
|
print("❌ Таблица 'audio' не существует в базе данных!")
|
||||||
|
print("💡 Запустите 'python init_db.py' для создания таблиц")
|
||||||
|
return False
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
def load(self):
|
def load(self):
|
||||||
|
# Проверяем БД перед началом работы
|
||||||
|
if not self.check_database():
|
||||||
|
exit(1)
|
||||||
|
|
||||||
date_now = datetime.datetime.now()# - datetime.timedelta(days=1)
|
date_now = datetime.datetime.now()# - datetime.timedelta(days=1)
|
||||||
remote_path = f"/{date_now.strftime('%Y/%m/%d')}"
|
remote_path = f"/{date_now.strftime('%Y/%m/%d')}"
|
||||||
|
|
||||||
@@ -40,13 +59,13 @@ class Loader():
|
|||||||
|
|
||||||
# Проверяем, существует ли файл локально
|
# Проверяем, существует ли файл локально
|
||||||
if os.path.exists(filepath):
|
if os.path.exists(filepath):
|
||||||
print(f"Файл уже существует: {file}")
|
print(f"Файл уже существует локально: {file}")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Скачиваем файл
|
# Скачиваем файл
|
||||||
sftp_client.get(remote_file, filepath)
|
sftp_client.get(remote_file, filepath)
|
||||||
print(f"Скачан файл: {remote_file}")
|
print(f"📥 Скачан файл: {remote_file}")
|
||||||
|
|
||||||
# Получаем размер файла
|
# Получаем размер файла
|
||||||
file_size = os.path.getsize(filepath)
|
file_size = os.path.getsize(filepath)
|
||||||
@@ -56,7 +75,7 @@ class Loader():
|
|||||||
# Проверяем, есть ли уже такой файл в БД
|
# Проверяем, есть ли уже такой файл в БД
|
||||||
existing_audio = db.query(Audio).filter(Audio.filename == file).first()
|
existing_audio = db.query(Audio).filter(Audio.filename == file).first()
|
||||||
if existing_audio:
|
if existing_audio:
|
||||||
print(f"Файл {file} уже есть в БД, пропускаем")
|
print(f"⏭️ Файл {file} уже есть в БД, пропускаем")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Создаём новую запись
|
# Создаём новую запись
|
||||||
|
|||||||
Executable
+39
@@ -0,0 +1,39 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
Скрипт для инициализации базы данных
|
||||||
|
Создаёт все необходимые таблицы
|
||||||
|
"""
|
||||||
|
from apiApp.database import Base, engine
|
||||||
|
from sqlalchemy import inspect
|
||||||
|
|
||||||
|
def init_database():
|
||||||
|
"""Создаёт все таблицы в базе данных"""
|
||||||
|
print("🔧 Инициализация базы данных...")
|
||||||
|
|
||||||
|
# Проверяем существующие таблицы
|
||||||
|
inspector = inspect(engine)
|
||||||
|
existing_tables = inspector.get_table_names()
|
||||||
|
|
||||||
|
if existing_tables:
|
||||||
|
print(f"📋 Существующие таблицы: {', '.join(existing_tables)}")
|
||||||
|
|
||||||
|
# Создаём все таблицы
|
||||||
|
Base.metadata.create_all(bind=engine)
|
||||||
|
|
||||||
|
# Проверяем результат
|
||||||
|
inspector = inspect(engine)
|
||||||
|
all_tables = inspector.get_table_names()
|
||||||
|
|
||||||
|
print(f"✅ Создано таблиц: {len(all_tables)}")
|
||||||
|
for table in all_tables:
|
||||||
|
print(f" - {table}")
|
||||||
|
|
||||||
|
return all_tables
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
try:
|
||||||
|
tables = init_database()
|
||||||
|
print(f"\n🎉 База данных готова! Создано таблиц: {len(tables)}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"\n❌ Ошибка при создании таблиц: {e}")
|
||||||
|
exit(1)
|
||||||
+9
-1
@@ -1,4 +1,12 @@
|
|||||||
from autoLoader import loader
|
from autoLoader import loader
|
||||||
|
from apiApp.database import Base, engine
|
||||||
|
|
||||||
|
# Создаём таблицы, если они не существуют
|
||||||
|
print("🔧 Создание таблиц базы данных...")
|
||||||
|
Base.metadata.create_all(bind=engine)
|
||||||
|
print("✅ Таблицы созданы")
|
||||||
|
|
||||||
loader.load()
|
# Запускаем загрузчик
|
||||||
|
print("\n🚀 Запуск AutoLoader...")
|
||||||
|
loader.load()
|
||||||
|
print("✅ AutoLoader завершил работу")
|
||||||
|
|||||||
Reference in New Issue
Block a user