]> git.ozlabs.org Git - patchwork/commitdiff
Add HashField.construct() method
authorJeremy Kerr <jk@ozlabs.org>
Thu, 11 Sep 2008 05:53:08 +0000 (15:53 +1000)
committerJeremy Kerr <jk@ozlabs.org>
Thu, 11 Sep 2008 05:53:08 +0000 (15:53 +1000)
To construct a new hash object for the given algorithm. While we're at
it, clean up the hashlib-wrapping code.

Signed-off-by: Jeremy Kerr <jk@ozlabs.org>
apps/patchwork/models.py

index 62ce59266b8a445a5c3a1516dd1fd4d83335b451..226a69c3a4037d64afbb3684189a2d446df8d3a5 100644 (file)
@@ -176,19 +176,19 @@ class HashField(models.CharField):
         self.algorithm = algorithm
         try:
             import hashlib
-            self.hashlib = True
+            def _construct(string = ''):
+                return hashlib.new(self.algorithm, string)
+            self.construct = _construct
             self.n_bytes = len(hashlib.new(self.algorithm).hexdigest())
         except ImportError:
-            self.hashlib = False
-            if algorithm == 'sha1':
-                import sha
-                hash_constructor = sha.new
-            elif algorithm == 'md5':
-                import md5
-                hash_constructor = md5.new
-            else:
+            modules = { 'sha1': 'sha', 'md5': 'md5'}
+
+            if algorithm not in modules.keys():
                 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
         super(HashField, self).__init__(*args, **kwargs)