# Create your tasks here
from __future__ import absolute_import, unicode_literals
from datetime import timedelta
from apps.monitor.models import DrfRequestLog
from apps.utils.tasks import CustomTask
from celery import shared_task
from django.utils import timezone
from django.conf import settings
import os


@shared_task(base=CustomTask)
def clear_drf_log(days: int = 7):
    """清除N天前的日志记录,默认七天

    清除N天前的日志记录
    """
    now = timezone.now()
    days7_ago = now - timedelta(days=days)
    DrfRequestLog.objects.filter(create_time__lte=days7_ago).delete()

@shared_task(base=CustomTask)
def clear_dbbackup(num: int=7):
    """
    清除N条前的数据库备份记录,默认七条

    清除N条前的数据库备份记录
    """
    from apps.monitor.views import get_file_list
    backpath = settings.BACKUP_PATH + '/database'
    files = get_file_list(backpath)
    files_remove_list = files[num:]
    for f in files_remove_list:
        filepath = os.path.join(backpath, f)
        os.remove(filepath)
