def extract_photo(request, archive_file, photo, album): # zipfile and tarfile are inconsistent if isinstance(photo, ZipInfo): photo_filename = photo.filename extract_file = archive_file.open elif isinstance(photo, tarfile.TarInfo): photo_filename = photo.name extract_file = archive_file.extractfile else: raise TypeError("'photo' must be a ZipInfo or TarInfo object.") # Ignore directories if not os.path.basename(photo_filename): return # Generate unique filename num = album.photo_set.count() filename, extension = os.path.splitext(photo_filename) new_filename = str(num).zfill(4) + extension photo_obj = Photo() photo_obj.album = album try: with extract_file(photo) as f: photo_obj.file.save(new_filename, File(f)) if not save_photo(photo_obj): messages.add_message(request, messages.WARNING, _("{} is duplicate.").format(photo_filename)) except (OSError, AttributeError, UnidentifiedImageError): messages.add_message(request, messages.WARNING, _("Ignoring {}").format(photo_filename)) if photo_obj.file.path: os.remove(photo_obj.file.path) photo_obj.delete()
def delete(self, request, pk, format=None): Photo = self.get_object(pk) Photo.delete() # Delete media? return Response(status=status.HTTP_204_NO_CONTENT)