From 7b9e8b1ee61b9211dc2c9dac59e29f4b7a5a7f15 Mon Sep 17 00:00:00 2001 From: Daniel Schadt Date: Mon, 18 Jul 2022 20:37:56 +0200 Subject: remove images when removing a track --- fietsboek/data.py | 20 ++++++++++++++++++++ fietsboek/views/detail.py | 2 ++ 2 files changed, 22 insertions(+) diff --git a/fietsboek/data.py b/fietsboek/data.py index 992ddf7..c1cd214 100644 --- a/fietsboek/data.py +++ b/fietsboek/data.py @@ -7,10 +7,14 @@ import random import string import shutil import uuid +import logging from .util import secure_filename +LOGGER = logging.getLogger(__name__) + + def generate_filename(filename): """Generates a safe-to-use filename for uploads. @@ -63,6 +67,22 @@ class DataManager: images.append(image.name) return images + def purge(self, track_id): + """Purge all data pertaining to the given track. + + This function logs errors but raises no exception, as such it can + always be used to clean up after a track. + + :param track_id: The ID of the track. + :type track_id: int + """ + def log_error(_, path, exc_info): + LOGGER.warning("Failed to remove %s", path, exc_info=exc_info) + + path = self._track_data_dir(track_id) + if path.is_dir(): + shutil.rmtree(path, ignore_errors=False, onerror=log_error) + def image_path(self, track_id, image_id): """Returns a path to a saved image. diff --git a/fietsboek/views/detail.py b/fietsboek/views/detail.py index 3953f47..0c72d64 100644 --- a/fietsboek/views/detail.py +++ b/fietsboek/views/detail.py @@ -73,7 +73,9 @@ def delete_track(request): :rtype: pyramid.response.Response """ track = request.context + track_id = track.id request.dbsession.delete(track) + request.data_manager.purge(track_id) request.session.flash(request.localizer.translate(_("flash.track_deleted"))) return HTTPFound(request.route_url('home')) -- cgit v1.2.3