What's the best way to rename photos with a unique filename on the server as they are uploaded, using django? I want to make sure each name is used only once. Are there any pinax apps that can do this, perhaps with GUID?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Django __str__ returned non-string (type NoneType)
- Evil ctypes hack in python
Prior to Django 1.6.6, 1.5.9, and 1.4.14, the
get_avaialable_name
function would automatically give files a unique name by adding an underscore. So, for example, if you save one file "test.jpg" and then another file, "test.jpg" to your server, the first will be called test.jpg, and the second will be called test_1.jpg.Alas, that turns out to be a vector for DDOSing a machine, by sending it thousands of zero-byte files to store, each one checking thousands of previous files to see what its name should be.
As you'll see in the docs, the new system appends seven random digits after the underscore to fix this problem.
As of the writing of this answer it seems like you no longer need to do anything special to make this happen. If you set up a FileField with a static upload_to property, the Django storage system will automatically manage naming so that if a duplicate filename is uploaded, Django will randomly generate a new unique filename for the duplicate.
Works on Django 1.10.
Use uuid. To tie that into your model see Django documentation for FileField upload_to.
For example in your models.py define the following function:
Then, when defining your FileField/ImageField, specify
get_file_path
as theupload_to
value.A better way could be using a common class in your helpers.py. This way you could reuse the random file generator across your apps.
In your helpers.py:
And then in your model just import the helper class:
And then use it:
Ref: https://coderwall.com/p/hfgoiw/give-imagefield-uploads-a-unique-name-to-avoid-file-overwrites
How about concatenating the filename with the date / time the photo was uploaded and then using hashlib to create a message digest? That should give you unique filenames.
Alternatively you could re-use a neat little snippet which creates unique filenames and then use the full path to that file as the input to your hash call. That gives you unique constant length strings which you can map to your files.