Update Celery configuration and add customer tasks
This commit is contained in:
44
myproject/customers/tasks.py
Normal file
44
myproject/customers/tasks.py
Normal file
@@ -0,0 +1,44 @@
|
||||
import os
|
||||
import re
|
||||
from datetime import datetime, timedelta
|
||||
from celery import shared_task
|
||||
from django.conf import settings
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@shared_task
|
||||
def delete_old_import_error_files():
|
||||
"""
|
||||
Удаляет файлы с ошибками импорта, которые не были скачаны пользователем в течение 24 часов.
|
||||
"""
|
||||
temp_imports_dir = os.path.join(settings.MEDIA_ROOT, 'temp_imports')
|
||||
if not os.path.exists(temp_imports_dir):
|
||||
logger.info(f"Директория {temp_imports_dir} не существует. Задача завершена.")
|
||||
return
|
||||
|
||||
current_time = datetime.now()
|
||||
files_deleted = 0
|
||||
|
||||
for filename in os.listdir(temp_imports_dir):
|
||||
file_path = os.path.join(temp_imports_dir, filename)
|
||||
if os.path.isfile(file_path):
|
||||
# Извлекаем дату и время из имени файла
|
||||
match = re.search(r'customer_import_errors_(\d{8})_(\d{6})\.xlsx', filename)
|
||||
if match:
|
||||
file_date_str = match.group(1)
|
||||
file_time_str = match.group(2)
|
||||
file_datetime = datetime.strptime(f"{file_date_str} {file_time_str}", "%Y%m%d %H%M%S")
|
||||
|
||||
# Проверяем, прошло ли 24 часа с момента создания файла
|
||||
if current_time - file_datetime > timedelta(hours=24):
|
||||
try:
|
||||
os.remove(file_path)
|
||||
files_deleted += 1
|
||||
logger.info(f"Удален файл: {file_path}")
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при удалении файла {file_path}: {e}")
|
||||
|
||||
logger.info(f"Удалено {files_deleted} устаревших файлов.")
|
||||
return files_deleted
|
||||
Reference in New Issue
Block a user