Django - 从亚马逊S3删除文件

时间:2013-12-11 10:25:53

标签: python django file amazon-web-services amazon-s3

我有一个问题,从管理员删除对象不会删除与之关联的文件。经过一些研究,我决定在模型中实现post_delete。 出于某种原因,我无法使s3删除文件,即使在搜索了大量的指南和片段后,也许有人知道。 我用django 1.5和boto。 继承我的模型代码:

from django.db import models
from django.contrib.auth.models import User
from fileservice.formatChecker import ContentTypeRestrictedFileField
from south.modelsinspector import add_introspection_rules
import os
from django.dispatch import receiver
from django.utils.translation import ugettext_lazy as _
from django.core.files.storage import default_storage as storage
add_introspection_rules([
    (
        [ContentTypeRestrictedFileField], # Class(es) these apply to
        [],         # Positional arguments (not used)
        {           # Keyword argument
            "content_types": ["content_types", {}],
            "max_upload_size": ["max_upload_size", {}]
        },
    ),
], ["^fileservice\.formatChecker\.ContentTypeRestrictedFileField"])

class Contentfile(models.Model):
    content = ContentTypeRestrictedFileField(upload_to='uploads/', content_types=['video/mp4', 'application/pdf', 'image/gif', 'image/jpeg', 'image/png'],max_upload_size=5242880,blank=True, null=True, help_text='Upload a file to add it to the content the app displayes')
    created_at = models.DateTimeField(auto_now_add=True, editable=False)
    updated_at = models.DateTimeField(auto_now=True, editable=False)
    title = models.CharField(max_length=255, unique=True)
    file_type = models.CharField(max_length=5)
    published = models.BooleanField(default=True)
    file_owner = models.ForeignKey(User, related_name='Contentfiles')

    class Meta:
        ordering = ["title"]

    def __unicode__(self):
        return self.title

    def save(self, *args, **kwargs):
        file_name = os.path.basename(self.content.name)
        self.file_type = file_name.split('.')[-1]
        self.title = file_name.split('.')[0]
        self.published = True
        super(Contentfile, self).save(*args, **kwargs)



@receiver(models.signals.post_delete, sender=Contentfile)
def auto_delete_file_on_delete(sender, instance, **kwargs):
    """Deletes file from filesystem
    when corresponding `MediaFile` object is deleted.
    """
    if instance.content:
        if os.path.isfile(storage.open(instance.content.path)):
            os.remove(storage.open(instance.content.path))

@receiver(models.signals.pre_save, sender=Contentfile)
def auto_delete_file_on_change(sender, instance, **kwargs):
    """Deletes file from filesystem
    when corresponding `MediaFile` object is changed.
    """
    if not instance.pk:
        return False

    try:
        old_file = Contentfile.objects.get(pk=instance.pk).content
    except Conentfile.DoesNotExist:
        return False

    new_file = instance.content
    if not old_file == new_file:
        if os.path.isfile(storage.open(old_file.path)):
            os.remove(storage.open(old_file.path))

4 个答案:

答案 0 :(得分:13)

做post_delete更安全。如果出现问题,您将开始丢失S3文件而您不会注意到它,因为您的数据库记录完好无损。 post_delete将更安全,因为删除db记录后S3删除操作失败的可能性较小。此外,即使文件删除失败,您仍会留下一堆未引用的S3文件,这些文件无害且可以轻松清理。

@receiver(models.signals.post_delete, sender=Picture)
def remove_file_from_s3(sender, instance, using, **kwargs):
    instance.img.delete(save=False)

答案 1 :(得分:10)

您需要调用FieldFile's delete()方法删除S3中的文件。在您的情况下,在您调用它时添加pre_delete信号:

@receiver(models.signals.pre_delete, sender=ContentFile)
def remove_file_from_s3(sender, instance, using):
    instance.content.delete(save=False)

答案 2 :(得分:2)

尝试django-cleanup,当您删除模型时,它会自动调用FileField上的delete方法。

答案 3 :(得分:0)

这通过删除数据库和AWS S3中的文件为我工作。

from django.db import models
from django.dispatch import receiver
from django.views import generic
from project.models import ContentFile
from django.contrib.auth.mixins import LoginRequiredMixin,UserPassesTestMixin

class DeleteFileView(LoginRequiredMixin,UserPassesTestMixin,generic.DeleteView):
   model = ContentFile
   template_name = 'file-delete.html'
   success_url = 'redirect-to'

   #Check if the owner of the file is the one trying to delete a file
   def test_func(self):
      obj = self.get_object()
      if obj.user == self.request.user:
        return True
      return False

    #This code does magic for S3 file deletion 
    @receiver(models.signals.pre_delete, sender=ContentFile)
    def remove_file_from_s3(sender, instance, using, **kwargs):
       instance.image_file.delete(save=False)

我正在使用pre_delete,您可以检查django documentation。数据库中的文件引用删除操作由DeleteView完成,希望对您有所帮助