Created
August 9, 2016 06:19
-
-
Save Alir3z4/725297248a59cae05a50b15dd79fb4d0 to your computer and use it in GitHub Desktop.
Create a hash of a file on upload time and save it for Django FileField/ImageField
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def hash_file(file, block_size=65536): | |
hasher = hashlib.md5() | |
for buf in iter(partial(file.read, block_size), b''): | |
hasher.update(buf) | |
return hasher.hexdigest() | |
def upload_to(instance, filename): | |
""" | |
:type instance: dolphin.models.File | |
""" | |
instance.file.open() | |
filename_base, filename_ext = os.path.splitext(filename) | |
return "{0}.{1}".format(hash_file(instance.file), filename_ext) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@harunurkst
Something like this:
Also, on line 16, you probably want
without the
.
Can confirm this still works on Django 3, with Blake2b, and
django-storages
:)