add write audio to db
This commit is contained in:
+44
-14
@@ -1,9 +1,10 @@
|
||||
from autoLoader.config import FILESAPTH
|
||||
from autoLoader.loader import ConnectorSFTP
|
||||
import datetime, os
|
||||
from autoLoader.database import *
|
||||
from autoLoader.database import Audio, get_db_session
|
||||
|
||||
local_path = os.path.join(os.getcwd(), FILESAPTH)
|
||||
|
||||
class Loader():
|
||||
def __init__(self):
|
||||
self.call_types = ['in']
|
||||
@@ -15,7 +16,6 @@ class Loader():
|
||||
return False
|
||||
|
||||
def load(self):
|
||||
|
||||
date_now = datetime.datetime.now()# - datetime.timedelta(days=1)
|
||||
remote_path = f"/{date_now.strftime('%Y/%m/%d')}"
|
||||
|
||||
@@ -29,30 +29,60 @@ class Loader():
|
||||
print("Не удалось подключиться к SFTP. Завершение работы.")
|
||||
exit(1)
|
||||
|
||||
db = get_db()
|
||||
|
||||
try:
|
||||
listdir = sftp_client.listdir()
|
||||
os.makedirs(local_path, exist_ok = True)
|
||||
diskdir = os.listdir(local_path)
|
||||
|
||||
|
||||
for file in listdir:
|
||||
if self.filter_call(filename=file):
|
||||
remote_file = f"{file}".lstrip('/')
|
||||
filepath = os.path.join(local_path, file)
|
||||
try:
|
||||
sftp_client.get(remote_file, filepath) # Скачиваем файл
|
||||
audio = Audio()
|
||||
audio.index_date = datetime.datetime.now()
|
||||
audio.filename = file
|
||||
db.session.add(audio)
|
||||
db.session.commit()
|
||||
|
||||
# Проверяем, существует ли файл локально
|
||||
if os.path.exists(filepath):
|
||||
print(f"Файл уже существует: {file}")
|
||||
continue
|
||||
|
||||
try:
|
||||
# Скачиваем файл
|
||||
sftp_client.get(remote_file, filepath)
|
||||
print(f"Скачан файл: {remote_file}")
|
||||
|
||||
# Получаем размер файла
|
||||
file_size = os.path.getsize(filepath)
|
||||
|
||||
# Сохраняем в БД через контекстный менеджер
|
||||
with get_db_session() as db:
|
||||
# Проверяем, есть ли уже такой файл в БД
|
||||
existing_audio = db.query(Audio).filter(Audio.filename == file).first()
|
||||
if existing_audio:
|
||||
print(f"Файл {file} уже есть в БД, пропускаем")
|
||||
continue
|
||||
|
||||
# Создаём новую запись
|
||||
audio = Audio()
|
||||
audio.index_date = datetime.datetime.now()
|
||||
audio.filename = file
|
||||
audio.file_path = filepath
|
||||
audio.file_size = file_size
|
||||
|
||||
db.add(audio)
|
||||
# commit произойдёт автоматически при выходе из контекста
|
||||
|
||||
print(f"✅ Файл {file} сохранён в БД")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Ошибка при скачивании файла {remote_file}: {e}")
|
||||
print(f"❌ Ошибка при обработке файла {remote_file}: {e}")
|
||||
# Если файл скачался, но ошибка в БД - удаляем файл
|
||||
if os.path.exists(filepath):
|
||||
try:
|
||||
os.remove(filepath)
|
||||
print(f"🗑️ Файл {file} удалён из-за ошибки")
|
||||
except:
|
||||
pass
|
||||
|
||||
finally:
|
||||
# Закрываем соединения
|
||||
sftp_client.close()
|
||||
ssh_client.close()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user