Fix address anonimization function on Python 2.
This commit is contained in:
parent
8801c6eec8
commit
0456d68f29
@ -19,6 +19,18 @@ class TestUtils(unittest.TestCase):
|
|||||||
for (addr, anonymized) in examples:
|
for (addr, anonymized) in examples:
|
||||||
self.assertEqual(utils.anonymize(addr), anonymized)
|
self.assertEqual(utils.anonymize(addr), anonymized)
|
||||||
|
|
||||||
|
def test_str(self):
|
||||||
|
# Accept a str on both Python 2 and Python 3, for
|
||||||
|
# convenience.
|
||||||
|
examples = [
|
||||||
|
('12.34.56.78', u'12.34.56.0'),
|
||||||
|
('1234:5678:90ab:cdef:fedc:ba09:8765:4321',
|
||||||
|
'1234:5678:90ab:0000:0000:0000:0000:0000'),
|
||||||
|
('::ffff:127.0.0.1', u'127.0.0.0')]
|
||||||
|
|
||||||
|
for (addr, anonymized) in examples:
|
||||||
|
self.assertEqual(utils.anonymize(addr), anonymized)
|
||||||
|
|
||||||
|
|
||||||
class TestParse(unittest.TestCase):
|
class TestParse(unittest.TestCase):
|
||||||
|
|
||||||
|
@ -14,6 +14,7 @@ from jinja2 import Environment, FileSystemLoader
|
|||||||
from werkzeug.wrappers import Response
|
from werkzeug.wrappers import Response
|
||||||
from werkzeug.exceptions import BadRequest
|
from werkzeug.exceptions import BadRequest
|
||||||
|
|
||||||
|
from isso.compat import text_type
|
||||||
from isso.wsgi import Request
|
from isso.wsgi import Request
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@ -28,6 +29,8 @@ def anonymize(remote_addr):
|
|||||||
and /48 (zero'd).
|
and /48 (zero'd).
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
if not isinstance(remote_addr, text_type) and isinstance(remote_addr, str):
|
||||||
|
remote_addr = remote_addr.decode('ascii', 'ignore')
|
||||||
try:
|
try:
|
||||||
ipv4 = ipaddress.IPv4Address(remote_addr)
|
ipv4 = ipaddress.IPv4Address(remote_addr)
|
||||||
return u''.join(ipv4.exploded.rsplit('.', 1)[0]) + '.' + '0'
|
return u''.join(ipv4.exploded.rsplit('.', 1)[0]) + '.' + '0'
|
||||||
@ -35,7 +38,7 @@ def anonymize(remote_addr):
|
|||||||
try:
|
try:
|
||||||
ipv6 = ipaddress.IPv6Address(remote_addr)
|
ipv6 = ipaddress.IPv6Address(remote_addr)
|
||||||
if ipv6.ipv4_mapped is not None:
|
if ipv6.ipv4_mapped is not None:
|
||||||
return anonymize(ipv6.ipv4_mapped)
|
return anonymize(text_type(ipv6.ipv4_mapped))
|
||||||
return u'' + ipv6.exploded.rsplit(':', 5)[0] + ':' + ':'.join(['0000'] * 5)
|
return u'' + ipv6.exploded.rsplit(':', 5)[0] + ':' + ':'.join(['0000'] * 5)
|
||||||
except ipaddress.AddressValueError:
|
except ipaddress.AddressValueError:
|
||||||
return u'0.0.0.0'
|
return u'0.0.0.0'
|
||||||
|
Loading…
Reference in New Issue
Block a user