django storages aws s3从模型记录中删除文件

时间:2017-11-19 13:04:18

标签: django amazon-web-services amazon-s3 delete-row django-storage

我已将{django aws S3解决方案基于https://simpleisbetterthancomplex.com/tutorial/2017/08/01/how-to-setup-amazon-s3-in-a-django-project.html

现在我正在尝试找到一种方法来删除包含S3文件的模型中的行。我可以使用.delete()删除该行,但它不会在S3中删除。

如何让删除行也在S3中删除?

以下是我的代码:

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/api.py

@api_view(['POST'])
def delete_employee(request):
    # ----- YAML below for Swagger -----
    """
    description: This API deletes employee
    parameters:
      - name: employee_id
        type: integer
        required: true
        location: form
    """
    employee_id = request.POST['employee_id']
    employee = Employee.objects.get(id = employee_id)
    logging.debug(f"API employee username {employee.username}")
    employee.delete() <---------- here is where the delete row happens
    return Response("Employee Deleted!", status=status.HTTP_200_OK)

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/models.py

class Employee(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employee')
    company = models.ForeignKey(Company)
    username = models.CharField(max_length=30, blank=False)
    upload = models.FileField(blank=True) <--- S3 field

https://gitlab.com/firdausmah/railercom/blob/master/railercom/settings.py(AWS设置)

AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME')
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
AWS_S3_OBJECT_PARAMETERS = {
    'CacheControl': 'max-age=86400',
}

DEFAULT_FILE_STORAGE = 'railercomapp.storage_backends.MediaStorage'

https://gitlab.com/firdausmah/railercom/blob/master/railercomapp/storage_backends.py     来自storages.backends.s3boto3导入S3Boto3Storage

class MediaStorage(S3Boto3Storage):
    location = 'media/yy'
    file_overwrite = False

2 个答案:

答案 0 :(得分:6)

您必须明确删除该文件。您可以编写删除后信号或在delete_employee函数中执行此操作。

employee.upload.delete(save=False)  # delete file
employee.delete()  # delete model instance

FileField.delete()的文档解释了这一点。

  

请注意,删除模型时,不会删除相关文件。如果您需要清理孤立文件,您需要自己处理它(例如,使用可以手动运行或计划通过例如cron定期运行的自定义管理命令)。

在删除之前,您还应该确保没有其他FileField引用完全相同的文件。

答案 1 :(得分:0)

我用了这个:

import boto3

client = boto3.client('s3')
client.delete_object(Bucket='mybucketname', Key='myfile.whatever')

但是我试图找到一种方法来处理模型的ImageFile对象,或者可能对存储类进行一些配置:

from storages.backends.s3boto3 import S3Boto3Storage 

class MediaStorage(S3Boto3Storage):    
    location = 'media'    
    file_overwrite = True