Used bytes.hex() and bytes.fromhex() to simplify.

This commit is contained in:
Sergey Fedoseev 2017-11-23 00:25:32 +05:00 committed by Tim Graham
parent 3f237c1a5b
commit 93cdd07e8f
6 changed files with 11 additions and 23 deletions

View File

@ -39,7 +39,7 @@
True True True True
""" """
import sys import sys
from binascii import a2b_hex, b2a_hex from binascii import b2a_hex
from ctypes import byref, c_char_p, c_double, c_ubyte, c_void_p, string_at from ctypes import byref, c_char_p, c_double, c_ubyte, c_void_p, string_at
from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.base import GDALBase
@ -67,7 +67,7 @@ class OGRGeometry(GDALBase):
# If HEX, unpack input to a binary buffer. # If HEX, unpack input to a binary buffer.
if str_instance and hex_regex.match(geom_input): if str_instance and hex_regex.match(geom_input):
geom_input = memoryview(a2b_hex(geom_input.upper().encode())) geom_input = memoryview(bytes.fromhex(geom_input))
str_instance = False str_instance = False
# Constructing the geometry, # Constructing the geometry,

View File

@ -1,11 +1,9 @@
import binascii
import copy import copy
import datetime import datetime
import re import re
from django.db.backends.base.schema import BaseDatabaseSchemaEditor from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.db.utils import DatabaseError from django.db.utils import DatabaseError
from django.utils.encoding import force_text
class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
@ -25,7 +23,7 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
elif isinstance(value, str): elif isinstance(value, str):
return "'%s'" % value.replace("\'", "\'\'") return "'%s'" % value.replace("\'", "\'\'")
elif isinstance(value, (bytes, bytearray, memoryview)): elif isinstance(value, (bytes, bytearray, memoryview)):
return "'%s'" % force_text(binascii.hexlify(value)) return "'%s'" % value.hex()
elif isinstance(value, bool): elif isinstance(value, bool):
return "1" if value else "0" return "1" if value else "0"
else: else:

View File

@ -1,4 +1,3 @@
import codecs
import contextlib import contextlib
import copy import copy
from decimal import Decimal from decimal import Decimal
@ -49,13 +48,8 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
elif isinstance(value, (bytes, bytearray, memoryview)): elif isinstance(value, (bytes, bytearray, memoryview)):
# Bytes are only allowed for BLOB fields, encoded as string # Bytes are only allowed for BLOB fields, encoded as string
# literals containing hexadecimal data and preceded by a single "X" # literals containing hexadecimal data and preceded by a single "X"
# character: # character.
# value = b'\x01\x02' => value_hex = b'0102' => return X'0102' return "X'%s'" % value.hex()
value = bytes(value)
hex_encoder = codecs.getencoder('hex_codec')
value_hex, _length = hex_encoder(value)
# Use 'ascii' encoding for b'01' => '01', no need to use force_text here.
return "X'%s'" % value_hex.decode('ascii')
else: else:
raise ValueError("Cannot quote parameter value %r of type %s" % (value, type(value))) raise ValueError("Cannot quote parameter value %r of type %s" % (value, type(value)))

View File

@ -1,6 +1,5 @@
import json import json
import pickle import pickle
from binascii import b2a_hex
from django.contrib.gis.gdal import ( from django.contrib.gis.gdal import (
CoordTransform, GDALException, OGRGeometry, OGRGeomType, SpatialReference, CoordTransform, GDALException, OGRGeometry, OGRGeomType, SpatialReference,
@ -100,7 +99,7 @@ class OGRGeomTest(SimpleTestCase, TestDataMixin):
for g in self.geometries.hex_wkt: for g in self.geometries.hex_wkt:
geom1 = OGRGeometry(g.wkt) geom1 = OGRGeometry(g.wkt)
wkb = geom1.wkb wkb = geom1.wkb
self.assertEqual(b2a_hex(wkb).upper(), g.hex.encode()) self.assertEqual(wkb.hex().upper(), g.hex)
# Constructing w/WKB. # Constructing w/WKB.
geom2 = OGRGeometry(wkb) geom2 = OGRGeometry(wkb)
self.assertEqual(geom1, geom2) self.assertEqual(geom1, geom2)

View File

@ -2,7 +2,7 @@ import ctypes
import json import json
import pickle import pickle
import random import random
from binascii import a2b_hex, b2a_hex from binascii import a2b_hex
from io import BytesIO from io import BytesIO
from unittest import mock from unittest import mock
@ -102,7 +102,7 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
for g in self.geometries.hex_wkt: for g in self.geometries.hex_wkt:
geom = fromstr(g.wkt) geom = fromstr(g.wkt)
wkb = geom.wkb wkb = geom.wkb
self.assertEqual(b2a_hex(wkb).decode().upper(), g.hex) self.assertEqual(wkb.hex().upper(), g.hex)
def test_create_hex(self): def test_create_hex(self):
"Testing creation from HEX." "Testing creation from HEX."
@ -115,7 +115,7 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
def test_create_wkb(self): def test_create_wkb(self):
"Testing creation from WKB." "Testing creation from WKB."
for g in self.geometries.hex_wkt: for g in self.geometries.hex_wkt:
wkb = memoryview(a2b_hex(g.hex.encode())) wkb = memoryview(bytes.fromhex(g.hex))
geom_h = GEOSGeometry(wkb) geom_h = GEOSGeometry(wkb)
# we need to do this so decimal places get normalized # we need to do this so decimal places get normalized
geom_t = fromstr(g.wkt) geom_t = fromstr(g.wkt)

View File

@ -1,4 +1,3 @@
import binascii
import hashlib import hashlib
import unittest import unittest
@ -132,14 +131,12 @@ class TestUtilsCryptoPBKDF2(unittest.TestCase):
def test_public_vectors(self): def test_public_vectors(self):
for vector in self.rfc_vectors: for vector in self.rfc_vectors:
result = pbkdf2(**vector['args']) result = pbkdf2(**vector['args'])
self.assertEqual(binascii.hexlify(result).decode('ascii'), self.assertEqual(result.hex(), vector['result'])
vector['result'])
def test_regression_vectors(self): def test_regression_vectors(self):
for vector in self.regression_vectors: for vector in self.regression_vectors:
result = pbkdf2(**vector['args']) result = pbkdf2(**vector['args'])
self.assertEqual(binascii.hexlify(result).decode('ascii'), self.assertEqual(result.hex(), vector['result'])
vector['result'])
def test_default_hmac_alg(self): def test_default_hmac_alg(self):
kwargs = {'password': b'password', 'salt': b'salt', 'iterations': 1, 'dklen': 20} kwargs = {'password': b'password', 'salt': b'salt', 'iterations': 1, 'dklen': 20}