Skip to content

Commit

Permalink
remove dependency on six
Browse files Browse the repository at this point in the history
as Python2 is not supported anymore, remove the
compatiblility layer provided by the six module

this fixes `TXT::test_parse` and `test_validate_strings`
by creating the proper output bytes in `_unescapify_from()`
  • Loading branch information
zeromind committed Feb 4, 2022
1 parent 9ef898d commit e92e477
Show file tree
Hide file tree
Showing 7 changed files with 21 additions and 25 deletions.
3 changes: 1 addition & 2 deletions dim/dim/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from datetime import datetime, timedelta

import flask_sqlalchemy
import six
import sqlalchemy.orm
import sqlalchemy.pool
from flask import Flask, g
Expand Down Expand Up @@ -178,7 +177,7 @@ def check_string_length(cls, key, inst):
max_length = col.type.length

def set_(instance, value, oldvalue, initiator):
if isinstance(value, six.string_types) and len(value) > max_length:
if isinstance(value, str) and len(value) > max_length:
raise InvalidParameterError("Field %s exceeds maximum length %d" % (col.name, max_length))
event.listen(inst, 'set', set_)

Expand Down
6 changes: 2 additions & 4 deletions dim/dim/ipaddr.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@


import six
from ipaddress import ip_address, IPv4Address, IPv6Address, ip_network


def valid_block(addr):
try:
ip_network(six.text_type(addr))
ip_network(str(addr))
return True
except ValueError:
return False
Expand All @@ -19,8 +18,7 @@ def __init__(self, address, prefix=None, version=None, auto_correct=False):
'''
:param auto_correct: if the address has bits set outside its netmask they will be cleared
'''
if isinstance(address, six.string_types):
address = six.text_type(address)
if isinstance(address, str):
s = address.split('/')
if len(s) > 2:
raise ValueError('Bad prefix')
Expand Down
7 changes: 3 additions & 4 deletions dim/dim/jsonrpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@

import requests
from flask import Blueprint, jsonify, json, request, session, current_app, abort, Response
from six import text_type

from . import ldap_auth
from dim import db
Expand Down Expand Up @@ -168,7 +167,7 @@ def jsonrpc_handler():
try:
json_request = json.loads(request.data)
except Exception as e:
return jsonify(error=dict(code=-32700, message='Parse error', data=text_type(e)),
return jsonify(error=dict(code=-32700, message='Parse error', data=str(e)),
**json_response)

json_response['id'] = json_request.get('id', None)
Expand All @@ -189,10 +188,10 @@ def jsonrpc_handler():
default=default_for_json)
except DimError as e:
logging.info('DimError: %s', e)
return jsonify(error=dict(code=e.code, message=text_type(e)), **json_response)
return jsonify(error=dict(code=e.code, message=str(e)), **json_response)
except Exception as e:
logging.exception(e)
return jsonify(error=dict(code=1, message=text_type(e)), **json_response)
return jsonify(error=dict(code=1, message=str(e)), **json_response)


def default_for_json(o):
Expand Down
3 changes: 1 addition & 2 deletions dim/dim/models/dns.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@

import flask.json as json
from flask import current_app as app, g
from six import text_type
from sqlalchemy import Column, ForeignKey, BigInteger, Integer, String, Boolean, TIMESTAMP, UniqueConstraint, func, desc, Text, Enum
from sqlalchemy.orm import relationship, validates, backref

Expand Down Expand Up @@ -369,7 +368,7 @@ def validate_args(type, **kwargs):
for field, validate in list(rr_class.validate.items()):
kwargs[field] = validate(None, field, kwargs[field])
except ValueError as e:
raise InvalidParameterError(text_type(e))
raise InvalidParameterError(str(e))
return kwargs

@staticmethod
Expand Down
9 changes: 4 additions & 5 deletions dim/dim/rpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import sys
import re

from six import text_type
import flask.json as json
from flask import current_app as app, g
from sqlalchemy import between, and_, or_, not_, select, String, desc
Expand Down Expand Up @@ -1181,7 +1180,7 @@ def ippool_add_subnet(self, pool, cidr,
try:
reserve(rip, pool.layer3domain)
except DimError as e:
Messages.info(text_type(e))
Messages.info(str(e))
block.set_attrs(attributes)
record_history(pool, action='create subnet', **_cidr(block))
if include_messages:
Expand Down Expand Up @@ -3128,9 +3127,9 @@ def delete_zone_or_view():
except DimError as e:
deleted = False
if delete_zone:
Messages.warn('Zone %s was not deleted: %s' % (name, text_type(e)))
Messages.warn('Zone %s was not deleted: %s' % (name, str(e)))
else:
Messages.warn('Zone %s view %s was not deleted: %s' % (name, view.name, text_type(e)))
Messages.warn('Zone %s view %s was not deleted: %s' % (name, view.name, str(e)))
else:
delete_zone_or_view()

Expand Down Expand Up @@ -3358,7 +3357,7 @@ def find_parent():
kwargs['ip'] = self._ip_mark(check_ip(ip, layer3domain, {'host': True}), layer3domain=layer3domain,
attributes=None, parse_rr=True, allow_overlap=allow_overlap)
else:
raise InvalidParameterError('Invalid IP %s: %s' % (kwargs['ip'], text_type(e)))
raise InvalidParameterError('Invalid IP %s: %s' % (kwargs['ip'], str(e)))
if rr_type == 'PTR' and ('ip' in kwargs) and ('name' not in kwargs):
kwargs['name'] = dim.dns.get_ptr_name(kwargs['ip'])

Expand Down
17 changes: 10 additions & 7 deletions dim/dim/rrtype.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
import re

import dns.rdata
from six import int2byte
from dim.errors import InvalidParameterError
from dim.messages import Messages
from dim.util import make_fqdn
from typing import Tuple, List, Union


def label_is_valid(label):
Expand Down Expand Up @@ -136,7 +136,7 @@ def validate_property_tag(self, key, value):
return value


def _unescapify_from(value, offset):
def _unescapify_from(value, offset: int) -> Tuple[bytes, int]:
'''
Unescape dns character string in value[offset:]. Returns a tuple of (bytearray unescaped_string,
the position where the processing of value stopped).
Expand All @@ -150,7 +150,7 @@ def _unescapify_from(value, offset):
The processing of value stops at the first unescaped double quote. This position is returned
along with the unescaped string created thus far.
'''
string = ''
string = b''
i = offset
while i < len(value):
if value[i] == '"':
Expand All @@ -161,18 +161,21 @@ def _unescapify_from(value, offset):
try:
escape_sequence = value[i]
if value[i + 1] in ('"', '\\'):
# escaped " or /
escape_sequence = value[i:i + 2]
string += str(value[i + 1])
string += str(value[i + 1]).encode('utf-8')
i += 2
else:
# assume escaped ordinal value (int) with a fixed length of 3
# e.g. \097 for the character a
escape_sequence = value[i:i + 4]
string += int2byte(int(value[i + 1:i + 4]))
string += bytes((int(value[i + 1:i + 4]),))
i += 4
except:
raise ValueError('Invalid escape sequence: %s' % escape_sequence)
else:
if 32 <= ord(value[i]) <= 126:
string += value[i]
string += value[i].encode('utf-8')
i += 1
else:
raise ValueError('Invalid character at position %d in: %s' % (i, value))
Expand Down Expand Up @@ -201,7 +204,7 @@ def _parse_strings(value):
return strings


def validate_strings(self, key, value):
def validate_strings(self, key, value: Union[str, List[str]]):
if isinstance(value, str):
strings = _parse_strings(value)
elif isinstance(value, list):
Expand Down
1 change: 0 additions & 1 deletion dim/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,3 @@ dnspython~=2.1
simplejson~=3.17
requests~=2.25
pycryptodome~=3.10
six

0 comments on commit e92e477

Please sign in to comment.