Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django-storages with Amazon S3 - prevent overwriting

I noticed that django-storages (or perhaps it's Django's storage API itself) overwrites files with the same name. This is a problem for me as my site allows user uploads, so I need to ensure that files are never overwritten.

Ideally I'd like to be able to pass a file name to the storage backend from the view level, but I'm struggling to find an elegant way to do this. I'd be equally happy if there's a switch somewhere where I can just do something like overwrite=False and have the backend come up with its own alternative name.

like image 693
Wayne Koorts Avatar asked Apr 25 '12 20:04

Wayne Koorts


People also ask

Does S3 overwrite?

Simply upload your new file on top of your old file to replace an old file in an S3 bucket. The existing file will be overwritten by your new file.

How can you ensure maximum protection of preserved versions in S3?

Amazon S3 further protects your data using versioning. You can use versioning to preserve, retrieve, and restore every version of every object that is stored in your Amazon S3 bucket. With versioning, you can easily recover from both unintended user actions and application failures.


2 Answers

If you are using the s3boto backend not the old s3 backend in django-storages then you can change this using the AWS_S3_FILE_OVERWRITE setting: https://bitbucket.org/david/django-storages/src/83fa2f0ba20c/storages/backends/s3boto.py#cl-43

like image 188
Mark Lavin Avatar answered Sep 20 '22 08:09

Mark Lavin


@Mark Lavin's answer aptly points out that setting AWS_S3_FILE_OVERWRITE to False avoids this problem.

You may additionally want to improve your file name-spacing a little bit. You can save files under whatever name on S3 you want (it doesn't have to be the name of the file the user uploaded). So you could save your file with the name "user_uploads/[user_id]/[user_generated_file_name]". You can also set the file name to be whatever you want as part of a download. If you save the user's uploaded file name as a field on your model, you can then specify that as the file name in the view that downloads a file.

like image 27
Zags Avatar answered Sep 19 '22 08:09

Zags