[PATCH v2 3/3] fields: Simplify HashField
Stephen Finucane
stephen.finucane at intel.com
Tue Mar 15 22:27:40 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>
---
v2: Add missing 'construct' method
---
patchwork/fields.py | 31 ++++++++++---------------------
1 file changed, 10 insertions(+), 21 deletions(-)
diff --git a/patchwork/fields.py b/patchwork/fields.py
index 96fdd28..c0a1b4d 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,30 +35,17 @@ 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 construct(self, value):
+ if isinstance(value, six.text_type):
+ value = value.encode('utf-8')
+ return hashlib.sha1(value)
+
def from_db_value(self, value, expression, connection, context):
return self.to_python(value)
--
2.0.0
More information about the Patchwork
mailing list