[PATCH 3/3] fields: Simplify HashField

Stephen Finucane stephen.finucane at intel.com
Sat Mar 12 06:29:11 AEDT 2016


The HashField was written to be configurable. It supports customisable
hash types and provides fallbacks for a missing 'hashlib', which was
only introduced in Python 2.5. However, the customisable hash types
are not used anywhere (the actual hashing is hardcoded to use 'sha1')
and Python 2.7/3.3+ are the only versions of Python currently
supported. As a result, it is possible to remove much of the code
without losing any real functionality. Do this.

Signed-off-by: Stephen Finucane <stephen.finucane at intel.com>
---
 patchwork/fields.py | 26 +++++---------------------
 1 file changed, 5 insertions(+), 21 deletions(-)

diff --git a/patchwork/fields.py b/patchwork/fields.py
index 96fdd28..8143434 100644
--- a/patchwork/fields.py
+++ b/patchwork/fields.py
@@ -20,6 +20,8 @@
 
 from __future__ import absolute_import
 
+import hashlib
+
 import django
 from django.db import models
 from django.utils import six
@@ -33,28 +35,10 @@ else:
 
 class HashField(HashFieldBase):
 
-    def __init__(self, algorithm='sha1', *args, **kwargs):
-        self.algorithm = algorithm
-        try:
-            import hashlib
-
-            def _construct(string=''):
-                if isinstance(string, six.text_type):
-                    string = string.encode('utf-8')
-                return hashlib.new(self.algorithm, string)
-            self.construct = _construct
-            self.n_bytes = len(hashlib.new(self.algorithm).hexdigest())
-        except ImportError:
-            modules = {'sha1': 'sha', 'md5': 'md5'}
-
-            if algorithm not in modules:
-                raise NameError("Unknown algorithm '%s'" % algorithm)
-
-            self.construct = __import__(modules[algorithm]).new
-
-        self.n_bytes = len(self.construct().hexdigest())
-
+    def __init__(self, *args, **kwargs):
+        self.n_bytes = len(hashlib.sha1().hexdigest())
         kwargs['max_length'] = self.n_bytes
+
         super(HashField, self).__init__(*args, **kwargs)
 
     def from_db_value(self, value, expression, connection, context):
-- 
2.0.0



More information about the Patchwork mailing list