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
|
||||||
@@ -1,34 +1,14 @@
|
|||||||
"""
|
from __future__ import absolute_import, unicode_literals
|
||||||
Celery configuration for myproject with django-tenants support.
|
|
||||||
|
|
||||||
IMPORTANT: В мультитенантной среде все задачи должны:
|
|
||||||
1. Получать schema_name в параметрах
|
|
||||||
2. Активировать нужную схему через connection.set_schema()
|
|
||||||
3. Это гарантирует изоляцию данных по тенантам
|
|
||||||
"""
|
|
||||||
import os
|
import os
|
||||||
import logging
|
|
||||||
from celery import Celery
|
from celery import Celery
|
||||||
from django.conf import settings
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
# Устанавливаем переменную окружения для настроек Django
|
||||||
|
|
||||||
# Указываем Django settings module
|
|
||||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
|
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
|
||||||
|
|
||||||
# Создаем Celery app
|
|
||||||
app = Celery('myproject')
|
app = Celery('myproject')
|
||||||
|
|
||||||
# Загружаем конфигурацию из Django settings с префиксом CELERY_
|
# Загружаем настройки из Django
|
||||||
app.config_from_object('django.conf:settings', namespace='CELERY')
|
app.config_from_object('django.conf:settings', namespace='CELERY')
|
||||||
|
|
||||||
# Автоматическое обнаружение tasks.py в приложениях
|
# Автоматическое обнаружение задач в приложениях Django
|
||||||
# Это позволяет использовать @shared_task в любом приложении
|
app.autodiscover_tasks()
|
||||||
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
|
|
||||||
|
|
||||||
|
|
||||||
@app.task(bind=True, ignore_result=True)
|
|
||||||
def debug_task(self):
|
|
||||||
"""Тестовая задача для проверки работы Celery"""
|
|
||||||
print(f'Request: {self.request!r}')
|
|
||||||
logger.info('Celery is working!')
|
|
||||||
|
|||||||
@@ -599,6 +599,11 @@ CELERY_BEAT_SCHEDULE = {
|
|||||||
'queue': 'photo_processing',
|
'queue': 'photo_processing',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
# Очистка устаревших файлов ошибок импорта клиентов каждый день в полночь
|
||||||
|
'delete-old-import-error-files-every-24-hours': {
|
||||||
|
'task': 'customers.tasks.delete_old_import_error_files',
|
||||||
|
'schedule': crontab(hour=0, minute=0), # Запускать каждый день в полночь
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
# ============================================
|
# ============================================
|
||||||
|
|||||||
Reference in New Issue
Block a user