import os
import re
from datetime import datetime, timedelta
import flask
from celery.task import Task as CeleryTask
from flask_babel import lazy_gettext as _
from .base import runner
from ..models import Task
[docs]class DataCleanupTask(CeleryTask):
"""Delete temporary files that have exceeded their lifetime."""
PARAM_LIFETIME = 'delete_older_than_minutes'
attribute_params = [
{
'key': PARAM_LIFETIME,
'label': _('Lebensdauer in Minuten'),
'datatype': 'integer',
},
]
@runner
def run(self, task, delete_older_than_minutes=None):
# Cleanup task executions
for task in Task.objects():
task.clean_executions()
# Remove all tmp files in upload-dir that are older then configured time to live
upload_dir = os.path.join(
flask.current_app.config['STATIC_ROOT'], 'upload')
for root, dirs, files in os.walk(upload_dir):
for the_file in files:
the_file_path = os.path.join(upload_dir, the_file)
# Check if filename matches tmp file
if not re.match('^xmm_.*_tmp__.*$', the_file):
continue
# Get file time of death
the_file_ctime = datetime.fromtimestamp(
os.path.getctime(the_file_path))
the_file_time_of_death = the_file_ctime + timedelta(
minutes=delete_older_than_minutes or 60)
# Check if time livetime exceeded and delete
if the_file_time_of_death < datetime.now():
flask.current_app.logger.info('Life of {} exceeded. File deleted.'.format(the_file_path))
os.remove(the_file_path)