Created
August 28, 2015 10:48
-
-
Save twidi/5eaea4c026a441091fc8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class Hashable(models.Model): | |
hash_method_prefix = 'compute_hash_' | |
default_hash_method = 'compute_hash_default' | |
hashable_fields = [] | |
class Meta: | |
abstract = True | |
def compute_hash_default(self, field_name, hash_function): | |
return hash_function(getattr(self, field_name), self) | |
def save(self, *args, **kwargs): | |
for hash_infos in self.hashable_fields: | |
field_name, hash_field_name = hash_infos[:2] | |
hash_function = hash_infos[2] if len(hash_infos) == 3 else None | |
hash_method = getattr(self, '%s%s' % (self.hash_method_prefix, field_name), | |
getattr(self, self.default_hash_method)) | |
setattr(self, hash_field_name, hash_method(field_name, hash_function)) | |
return super().save(*args, **kwargs) | |
# instance not needed by default but we could imagine some use case | |
def md5_hash_file(file_field, instance, default=settings.EMPTY_FILE_HASH): | |
try: | |
md5 = hashlib.md5() | |
for chunk in file_field.chunks(): | |
md5.update(chunk) | |
return md5.hexdigest() | |
except: | |
return default | |
class MyModel(Hashable): | |
img = models.ImageField(...) | |
hash = models.CharField(...) | |
hashable_fields = [ | |
('img', 'hash', md5_hash_file) | |
] | |
class OtherModel(Hashable): | |
file = models.FileField(...) | |
hash_file = models.CharField(...) | |
file2 = models.FileField(...) | |
hash_file2 = models.CharFiel(...) | |
hashable_fields = [ | |
('file', 'hash_file', md5_hash_file), | |
('file2', 'hash_file2') | |
] | |
def compute_hash_file2(self, file_name, hash_function): | |
# here some complicated code | |
return some_hash |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment