From: Stephen Finucane Date: Fri, 11 Mar 2016 18:31:01 +0000 (+0000) Subject: fields: Simplify HashField X-Git-Tag: v2.0.0-rc1~416 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=16f3f9b0f881e2660603c57e7fd7ac648ab44fd1;p=thirdparty%2Fpatchwork.git fields: Simplify HashField 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 Reviewed-by: Andy Doan --- diff --git a/patchwork/fields.py b/patchwork/fields.py index 96fdd280..c0a1b4d8 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)