Files
octopus/myproject/customers/tasks.py

44 lines
1.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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