def delete_album(album_id): """Page for deleting an album.""" album = session.query(Album).filter_by(id=album_id).one() # protect page from unauthorized people using url to directly access: if login_session['user_id'] != album.user_id: return alert_script("delete this album") if request.method == 'POST': # we want to delete all items recursively when we delete an album: album_images = session.query(Image).filter_by(album_id=album_id).all() for x in album_images: session.delete(x) # try committing changes: if not commit_changes(album, 'delete'): return redirect(url_for('show_albums')) # delete media folder: shutil.rmtree(album.file_path) # flash message: flash("Album successfully deleted") return redirect(url_for('show_albums')) else: return render_template('deleteAlbum.html', album=album, title='Delete Album')
def commit_changes(item, crud_function='add'): """Commit CRUD changes with proper error catching.""" try: if crud_function == 'add': session.add(item) else: session.delete(item) session.commit() return True except IntegrityError as e: session.rollback() flash("An error occurred while trying to %s" % crud_function) return None