Commit 0deabd40 authored by Jeremy Kerr's avatar Jeremy Kerr
Browse files

Add HashField.construct() method

To construct a new hash object for the given algorithm. While we're at
it, clean up the hashlib-wrapping code.

Signed-off-by: default avatarJeremy Kerr <>
parent 7cc12f61
...@@ -176,19 +176,19 @@ class HashField(models.CharField): ...@@ -176,19 +176,19 @@ class HashField(models.CharField):
self.algorithm = algorithm self.algorithm = algorithm
try: try:
import hashlib import hashlib
self.hashlib = True def _construct(string = ''):
return, string)
self.construct = _construct
self.n_bytes = len( self.n_bytes = len(
except ImportError: except ImportError:
self.hashlib = False modules = { 'sha1': 'sha', 'md5': 'md5'}
if algorithm == 'sha1':
import sha if algorithm not in modules.keys():
hash_constructor =
elif algorithm == 'md5':
import md5
hash_constructor =
raise NameError("Unknown algorithm '%s'" % algorithm) raise NameError("Unknown algorithm '%s'" % algorithm)
self.n_bytes = len(hash_constructor().hexdigest())
self.construct = __import__(modules[algorithm]).new
self.n_bytes = len(self.construct().hexdigest())
kwargs['max_length'] = self.n_bytes kwargs['max_length'] = self.n_bytes
super(HashField, self).__init__(*args, **kwargs) super(HashField, self).__init__(*args, **kwargs)
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment