remove six and drop support of python 2

This commit is contained in:
ziirish 2018-06-06 18:29:08 +02:00
parent 64860e8bf6
commit 9b8cceed17
No known key found for this signature in database
GPG key ID: 72DB229A64B54E46
32 changed files with 133 additions and 175 deletions

View file

@ -8,7 +8,6 @@
"""
import ujson
from six import viewkeys
__implements__ = ['dumps', 'loads']
ori_dumps = None
@ -30,7 +29,7 @@ IMPLEMENTED_LOADS_KWARGS = [
def dumps(*args, **kwargs):
keys = []
if kwargs:
keys = viewkeys(kwargs)
keys = kwargs.keys()
for key in keys:
if key not in IMPLEMENTED_DUMPS_KWARGS:
return ori_dumps(*args, **kwargs)
@ -43,7 +42,7 @@ def dumps(*args, **kwargs):
def loads(*args, **kwargs):
keys = []
if kwargs:
keys = viewkeys(kwargs)
keys = kwargs.keys()
for key in keys:
if key not in IMPLEMENTED_LOADS_KWARGS:
return ori_loads(*args, **kwargs)

View file

@ -15,7 +15,6 @@ from ..utils import NOTIF_OK
from .custom import fields, Resource
# from ..exceptions import BUIserverException
from six import iteritems
from flask import current_app
from flask_login import current_user
from flask_babel import gettext
@ -215,7 +214,7 @@ class AclAdminss(Resource):
if not handler or len(handler.backends) == 0:
self.abort(404, "No acl backend found")
ret = []
for _, loader in iteritems(handler.backends):
for _, loader in handler.backends.items():
append = {
'members': loader.admins,
'backend': loader.name
@ -454,7 +453,7 @@ class AclModerators(Resource):
if not handler or len(handler.backends) == 0:
self.abort(404, "No acl backend found")
ret = []
for _, loader in iteritems(handler.backends):
for _, loader in handler.backends.items():
append = {
'grant': loader.moderator,
'members': loader.moderators,
@ -899,10 +898,10 @@ class AclGroups(Resource):
if not handler or len(handler.backends) == 0:
self.abort(404, "No acl backend found")
ret = []
for _, loader in iteritems(handler.backends):
for _, loader in handler.backends.items():
groups = loader.groups
if groups:
for _id, group in iteritems(groups):
for _id, group in groups.items():
append = {
'id': _id.lstrip('@'),
'grant': group.get('grants', ''),
@ -1097,10 +1096,10 @@ class AclGrants(Resource):
if not handler or len(handler.backends) == 0:
self.abort(404, "No acl backend found")
ret = []
for _, loader in iteritems(handler.backends):
for _, loader in handler.backends.items():
grants = loader.grants
if grants:
for _id, grant in iteritems(grants):
for _id, grant in grants.items():
append = {
'id': _id,
'grant': json.dumps(grant),
@ -1316,7 +1315,7 @@ class AclBackends(Resource):
if not handler or len(handler.backends) == 0:
self.abort(404, "No authentication backend found")
ret = []
for name, backend in iteritems(handler.backends):
for name, backend in handler.backends.items():
back = {}
back['name'] = name
back['description'] = gettext(backend.__doc__)
@ -1383,7 +1382,7 @@ class AuthUsers(Resource):
if not handler or len(handler.backends) == 0:
self.abort(404, "No authentication backend found")
ret = []
for _, backend in iteritems(handler.backends):
for _, backend in handler.backends.items():
loader = backend.loader
try:
users = getattr(loader, 'users')
@ -1402,7 +1401,7 @@ class AuthUsers(Resource):
return append
ret.append(append)
elif isinstance(users, dict):
for user, _ in iteritems(users):
for user, _ in users.items():
append = {
'id': backend.user(user).get_id(),
'name': user,
@ -1630,7 +1629,7 @@ class AuthBackends(Resource):
if not handler or len(handler.backends) == 0:
self.abort(404, "No authentication backend found")
ret = []
for name, backend in iteritems(handler.backends):
for name, backend in handler.backends.items():
ret.append({
'name': name,
'description': gettext(backend.__doc__),

View file

@ -18,7 +18,6 @@ from ..ext.cache import cache
from ..exceptions import BUIserverException
from ..utils import NOTIF_ERROR
from six import iteritems
from flask_restplus.marshalling import marshal
from flask import current_app, request
from flask_login import current_user
@ -325,7 +324,7 @@ class ClientTree(Resource):
# /!\ after marshalling, 'fullname' will be 'key'
tree[entry['fullname']] = marshal(entry, node_fields)
for key, entry in iteritems(tree):
for key, entry in tree.items():
parent = entry['parent']
if not entry['children']:
entry['children'] = None
@ -476,7 +475,7 @@ class ClientTreeAll(Resource):
redo = True
while redo:
redo = False
for key, entry in iteritems(tree):
for key, entry in tree.items():
parent = entry['parent']
if not entry['children']:
entry['children'] = None

View file

@ -15,7 +15,6 @@ from ..ext.cache import cache
from ..exceptions import BUIserverException
from ..decorators import browser_cache
from six import iteritems
from flask import current_app
from flask_login import current_user
@ -187,7 +186,7 @@ class RunningBackup(Resource):
res = [x for x in res if x in allowed]
running = False
if isinstance(res, dict):
for (_, run) in iteritems(res):
for (_, run) in res.items():
running = running or (len(run) > 0)
if running:
break
@ -627,7 +626,7 @@ class AllClients(Resource):
else:
for serv in bui.client.servers:
grants[serv] = 'all'
for (serv, clients) in iteritems(grants):
for (serv, clients) in grants.items():
if not isinstance(clients, list):
clients = clients_cache.get(serv, [])
ret += [{'name': x, 'agent': serv} for x in clients]

View file

@ -15,7 +15,6 @@ from ..decorators import browser_cache
from ..ext.cache import cache
from ..ext.i18n import LANGUAGES
from six import iteritems
from flask import flash, url_for, current_app, session
from flask_login import current_user
@ -121,7 +120,7 @@ class Counters(Resource):
self.abort(404, "'{}' not found in the list of running clients for '{}'".format(client, server))
else:
found = False
for (_, cls) in iteritems(running):
for (_, cls) in running.items():
if client in cls:
found = True
break
@ -229,7 +228,7 @@ class Live(Resource):
else:
running = bui.client.is_one_backup_running()
if isinstance(running, dict):
for (serv, clients) in iteritems(running):
for (serv, clients) in running.items():
for client in clients:
# ACL
if has_acl and not is_admin and \
@ -385,15 +384,15 @@ class About(Resource):
srv = bui.client.get_server_version(server)
multi = {}
if isinstance(cli, dict):
for (name, val) in iteritems(cli):
for (name, val) in cli.items():
multi[name] = {'client': val}
if isinstance(srv, dict):
for (name, val) in iteritems(srv):
for (name, val) in srv.items():
multi[name]['server'] = val
if not multi:
res['burp'].append({'client': cli, 'server': srv})
else:
for (name, val) in iteritems(multi):
for (name, val) in multi.items():
tmp = val
tmp.update({'name': name})
res['burp'].append(tmp)
@ -653,7 +652,7 @@ class History(Resource):
grants[serv] = [x for x in all_clients if current_user.acl.is_client_allowed(x, serv)]
else:
grants[serv] = 'all'
for (serv, clients) in iteritems(grants):
for (serv, clients) in grants.items():
if not isinstance(clients, list):
if data and serv in data:
clients = data[serv].keys()

View file

@ -7,7 +7,6 @@
.. moduleauthor:: Ziirish <hi+burpui@ziirish.me>
"""
from six import viewkeys
from flask import session, current_app, request
from flask_login import current_user
from werkzeug.datastructures import MultiDict
@ -85,7 +84,7 @@ class PrefsUI(Resource):
data = getattr(request, loc, None)
if data:
req.update(data)
for key in viewkeys(args):
for key in args.keys():
if key not in req:
continue
temp = args.get(key)
@ -117,7 +116,7 @@ class PrefsUI(Resource):
args = self.parser.parse_args()
ret = {}
sess = session
for key in viewkeys(args):
for key in args.keys():
ret[key] = sess.get(key)
return ret
@ -150,7 +149,7 @@ class PrefsUI(Resource):
args = self.parser.parse_args()
sess = session
ret = {}
for key in viewkeys(args):
for key in args.keys():
temp = args.get(key)
if temp:
del sess[key]

View file

@ -10,7 +10,6 @@ from ..exceptions import BUIserverException
from flask import current_app
from flask_login import current_user
from six import iteritems
bui = current_app # type: BUIServer
ns = api.namespace('servers', 'Servers methods')
@ -211,7 +210,7 @@ class ServersReport(Resource):
else:
os[stats['stats']['os']] = 1
for key, val in iteritems(os):
for key, val in os.items():
out['stats']['os'][key] = val
for bkp in j['backups']:

View file

@ -14,7 +14,6 @@ from .custom import Resource, inputs
from .._compat import unquote
from ..utils import NOTIF_INFO
from six import iteritems
from flask_babel import gettext as _, refresh
from flask import jsonify, request, url_for, current_app, g, session
from flask_login import current_user
@ -267,12 +266,12 @@ class ServerSettings(Resource):
'pair_associations': '_pair_associations_parser_{}'.format(server),
}
cache_results = {}
for name, key in iteritems(cache_keys):
for name, key in cache_keys.items():
if not cache.cache.has(key):
if name in ['doc', 'placeholders']:
_tmp = bui.client.get_parser_attr(name, server).copy()
_tmp2 = {}
for k, v in iteritems(_tmp):
for k, v in _tmp.items():
_tmp2[k] = _(v)
cache_results[name] = _tmp2
else:
@ -538,12 +537,12 @@ class ClientSettings(Resource):
'defaults': '_defaults_parser_{}'.format(server),
}
cache_results = {}
for name, key in iteritems(cache_keys):
for name, key in cache_keys.items():
if not cache.cache.has(key):
if name in ['doc', 'placeholders']:
_tmp = bui.client.get_parser_attr(name, server).copy()
_tmp2 = {}
for k, v in iteritems(_tmp):
for k, v in _tmp.items():
_tmp2[k] = _(v)
cache_results[name] = _tmp2
else:

View file

@ -22,7 +22,6 @@ if os.getenv('BUI_MODE') in ['server', 'ws'] or 'websocket' in sys.argv:
from .app import create_app # noqa
from .exceptions import BUIserverException # noqa
from six import iteritems # noqa
try:
from flask_socketio import SocketIO # noqa
@ -45,21 +44,16 @@ if VERBOSE:
UNITTEST = os.getenv('BUI_MODE') not in ['server', 'manage', 'celery', 'legacy', 'ws']
CLI = os.getenv('BUI_MODE') not in ['server', 'legacy']
try:
app = create_app(
conf=os.environ.get('BUI_CONFIG'),
verbose=VERBOSE,
logfile=os.environ.get('BUI_LOGFILE'),
debug=DEBUG,
gunicorn=False,
unittest=UNITTEST,
cli=CLI,
websocket_server=(os.getenv('BUI_MODE') == 'ws' or 'websocket' in sys.argv)
)
except:
import traceback
traceback.print_exc()
sys.exit(1)
app = create_app(
conf=os.environ.get('BUI_CONFIG'),
verbose=VERBOSE,
logfile=os.environ.get('BUI_LOGFILE'),
debug=DEBUG,
gunicorn=False,
unittest=UNITTEST,
cli=CLI,
websocket_server=(os.getenv('BUI_MODE') == 'ws' or 'websocket' in sys.argv)
)
try:
from .app import create_db
@ -1146,7 +1140,7 @@ def sysinfo(verbose, load):
if load:
if not app.config['STANDALONE'] and not msg:
click.echo('Agents:')
for agent, obj in iteritems(app.client.servers):
for agent, obj in app.client.servers.items():
client_version = server_version = 'unknown'
try:
app.client.status(agent=agent)
@ -1188,7 +1182,7 @@ def sysinfo(verbose, load):
if section in app.config.options:
click.echo()
click.echo(' 8<{}BEGIN[{}]'.format('-' * (67 - len(section)), section))
for key, val in iteritems(app.config.options.get(section, {})):
for key, val in app.config.options.get(section, {}).items():
click.echo(' {} = {}'.format(key, val))
click.echo(' 8<{}END[{}]'.format('-' * (69 - len(section)), section))

View file

@ -12,8 +12,6 @@
from copy import deepcopy
from itertools import repeat
from six import iterkeys, itervalues, iteritems, iterlists
def is_immutable(self):
raise TypeError('%r objects are immutable' % self.__class__.__name__)
@ -24,10 +22,10 @@ def iter_multi_items(mapping):
without dropping any from more complex structures.
"""
if isinstance(mapping, MultiDict):
for item in iteritems(mapping, multi=True):
for item in mapping.items(multi=True):
yield item
elif isinstance(mapping, dict):
for key, value in iteritems(mapping):
for key, value in mapping.items():
if isinstance(value, (tuple, list)):
for value in value:
yield key, value
@ -74,7 +72,7 @@ class ImmutableDictMixin(object):
return type(self), (dict(self),)
def _iter_hashitems(self):
return iteritems(self)
return self.items()
def __hash__(self):
if self._hash_cache is not None:
@ -114,10 +112,10 @@ class ImmutableMultiDictMixin(ImmutableDictMixin):
"""
def __reduce_ex__(self, protocol):
return type(self), (list(iteritems(self, multi=True)),)
return type(self), (list(self.items(multi=True)),)
def _iter_hashitems(self):
return iteritems(self, multi=True)
return self.items(multi=True)
def add(self, key, value):
is_immutable(self)
@ -238,10 +236,10 @@ class MultiDict(TypeConversionDict):
def __init__(self, mapping=None):
if isinstance(mapping, MultiDict):
dict.__init__(self, ((k, l[:]) for k, l in iterlists(mapping)))
dict.__init__(self, ((k, l[:]) for k, l in mapping.lists()))
elif isinstance(mapping, dict):
tmp = {}
for key, value in iteritems(mapping):
for key, value in mapping.items():
if isinstance(value, (tuple, list)):
if len(value) == 0:
continue
@ -384,7 +382,7 @@ class MultiDict(TypeConversionDict):
contain pairs for the first value of each key.
"""
for key, values in iteritems(dict, self):
for key, values in dict.items(self):
if multi:
for value in values:
yield key, value
@ -395,17 +393,17 @@ class MultiDict(TypeConversionDict):
"""Return a list of ``(key, values)`` pairs, where values is the list
of all values associated with the key."""
for key, values in iteritems(dict, self):
for key, values in dict.items(self):
yield key, list(values)
def keys(self):
return iterkeys(dict, self)
return dict.keys(self)
__iter__ = keys
def values(self):
"""Returns an iterator of the first value on every key's value list."""
for values in itervalues(dict, self):
for values in dict.values(self):
yield values[0]
def listvalues(self):
@ -417,7 +415,7 @@ class MultiDict(TypeConversionDict):
True
"""
return itervalues(dict, self)
return dict.values(self)
def copy(self):
"""Return a shallow copy of this object."""
@ -438,7 +436,7 @@ class MultiDict(TypeConversionDict):
:return: a :class:`dict`
"""
if flat:
return dict(iteritems(self))
return dict(self.items())
return dict(self.lists())
def update(self, other_dict):
@ -518,7 +516,7 @@ class MultiDict(TypeConversionDict):
return self.deepcopy(memo=memo)
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, list(iteritems(self, multi=True)))
return '%s(%r)' % (self.__class__.__name__, list(self.items(multi=True)))
class _omd_bucket(object):
@ -581,8 +579,8 @@ class OrderedMultiDict(MultiDict):
if not isinstance(other, MultiDict):
return NotImplemented
if isinstance(other, OrderedMultiDict):
iter1 = iteritems(self, multi=True)
iter2 = iteritems(other, multi=True)
iter1 = self.items(multi=True)
iter2 = other.items(multi=True)
try:
for k1, v1 in iter1:
k2, v2 = next(iter2)
@ -597,7 +595,7 @@ class OrderedMultiDict(MultiDict):
return False
if len(self) != len(other):
return False
for key, values in iterlists(self):
for key, values in self.lists():
if other.getlist(key) != values:
return False
return True
@ -608,10 +606,10 @@ class OrderedMultiDict(MultiDict):
return not self.__eq__(other)
def __reduce_ex__(self, protocol):
return type(self), (list(iteritems(self, multi=True)),)
return type(self), (list(self.items(multi=True)),)
def __getstate__(self):
return list(iteritems(self, multi=True))
return list(self.items(multi=True))
def __setstate__(self, values):
dict.clear(self)
@ -631,12 +629,12 @@ class OrderedMultiDict(MultiDict):
self.pop(key)
def keys(self):
return (key for key, value in iteritems(self))
return (key for key, value in self.items())
__iter__ = keys
def values(self):
return (value for key, value in iteritems(self))
return (value for key, value in self.items())
def items(self, multi=False):
ptr = self._first_bucket
@ -662,7 +660,7 @@ class OrderedMultiDict(MultiDict):
ptr = ptr.next
def listvalues(self):
for key, values in iterlists(self):
for key, values in self.lists():
yield values
def add(self, key, value):
@ -776,7 +774,7 @@ class ImmutableOrderedMultiDict(ImmutableMultiDictMixin, OrderedMultiDict):
"""
def _iter_hashitems(self):
return enumerate(iteritems(self, multi=True))
return enumerate(self.items(multi=True))
def copy(self):
"""Return a shallow mutable copy of this object. Keep in mind that

View file

@ -1,6 +1,4 @@
# -*- coding: utf8 -*-
from six import iteritems
from .meta import meta_grants, BUIaclGrant
from .interface import BUIaclLoader
from ...utils import NOTIF_OK, NOTIF_WARN, NOTIF_ERROR, __
@ -184,7 +182,7 @@ class ACLloader(BUIaclLoader):
self.del_admin(name)
if name in self.moderators:
self.del_moderator(name)
for group, members in iteritems(self._groups):
for group, members in self._groups.items():
if name in members:
self.del_group_member(group, name)
message = "grant '{}' successfully removed".format(name)
@ -249,7 +247,7 @@ class ACLloader(BUIaclLoader):
self.del_admin(gname)
if gname in self.moderators:
self.del_moderator(gname)
for group, members in iteritems(self._groups):
for group, members in self._groups.items():
if gname in members:
self.del_group_member(group, gname)
message = "grant '{}' successfully removed".format(name)

View file

@ -5,7 +5,6 @@ from .interface import BUIacl, BUIaclLoader
from .meta import meta_grants
from importlib import import_module
from six import iteritems
from collections import OrderedDict
@ -70,7 +69,7 @@ class ACLloader(BUIaclLoader):
except:
import traceback
self.errors[au] = traceback.format_exc()
for name, plugin in iteritems(self.app.plugin_manager.get_plugins_by_type('acl')):
for name, plugin in self.app.plugin_manager.get_plugins_by_type('acl').items():
try:
obj = plugin.ACLloader(self.app)
backends.append(obj)
@ -83,7 +82,7 @@ class ACLloader(BUIaclLoader):
'No backend found for \'{}\':\n{}'.format(self.app.acl_engine,
self.errors)
)
for name, err in iteritems(self.errors):
for name, err in self.errors.items():
self.app.logger.error(
'Unable to load module {}:\n{}'.format(repr(name), err)
)
@ -120,7 +119,7 @@ class ACLhandler(BUIacl):
def _iterate_through_loader(self, method, *args, **kwargs):
ret = None
for _, acl_engine in iteritems(self.loader.backends):
for _, acl_engine in self.loader.backends.items():
func = getattr(acl_engine.acl, method)
ret = func(*args, **kwargs)
if isinstance(ret, tuple):

View file

@ -8,12 +8,11 @@
"""
from abc import ABCMeta, abstractmethod, abstractproperty
from six import with_metaclass
import logging
class BUIaclLoader(with_metaclass(ABCMeta, object)):
class BUIaclLoader(object, metaclass=ABCMeta):
"""The :class:`burpui.misc.acl.interface.BUIaclLoader` class is used to
load the actual ACL backend"""
@ -82,7 +81,7 @@ class BUIaclLoader(with_metaclass(ABCMeta, object)):
return None # pragma: no cover
class BUIacl(with_metaclass(ABCMeta, object)):
class BUIacl(object, metaclass=ABCMeta):
"""The :class:`burpui.misc.acl.interface.BUIacl` class represents the ACL
engine.
"""

View file

@ -12,8 +12,6 @@ from ...utils import make_list
from ...config import config
from ...ext.cache import cache
from six import iteritems, itervalues
import re
import json
import fnmatch
@ -48,7 +46,7 @@ class BUImetaGrant(object):
return [d1, d2]
res = d1
for key2, val2 in iteritems(d2):
for key2, val2 in d2.items():
if key2 in res:
res[key2] = self._merge_data(val2, res[key2])
else:
@ -72,7 +70,7 @@ class BUImetaGrant(object):
else:
advanced[mode] = {'clients': make_list(data)}
return make_list(data), agents, advanced
for key, val in iteritems(data):
for key, val in data.items():
if key in ['agents', 'clients', 'ro', 'rw']:
continue
cl1, ag1, ad1 = self._parse_clients(val, parent=key)
@ -127,7 +125,7 @@ class BUImetaGrant(object):
if mode:
advanced[mode] = {'agents': make_list(data)}
return make_list(data), clients, advanced
for key, val in iteritems(data):
for key, val in data.items():
if key in ['agents', 'clients', 'ro', 'rw']:
continue
cl1, ag1, ad1 = self._parse_clients(data)
@ -215,7 +213,7 @@ class BUIgrantHandler(BUImetaGrant, BUIacl):
self._groups.clear()
self._reset_cached()
self._id += 1
for name, backend in iteritems(self._backends):
for name, backend in self._backends.items():
if name == reset_from:
continue
backend.reload()
@ -265,7 +263,7 @@ class BUIgrantHandler(BUImetaGrant, BUIacl):
def get_member_groups(self, member):
groups = []
for group in itervalues(self._groups):
for group in self._groups.values():
(ret, inh) = group.is_member(member)
if ret and group.name not in self._gp_hidden:
groups.append((group.name, inh))
@ -318,7 +316,7 @@ class BUIgrantHandler(BUImetaGrant, BUIacl):
data['advanced'] += tmp
# moderator is also a group
for gname, group in iteritems(self.groups):
for gname, group in self.groups.items():
# no grants need to be parsed for admins
if gname == self._gp_admin_name:
continue

View file

@ -8,7 +8,6 @@ from ..acl.interface import BUIacl
from importlib import import_module
from flask import session
from six import iteritems
from collections import OrderedDict
from flask_login import AnonymousUserMixin
@ -42,7 +41,7 @@ class UserAuthHandler(BUIhandler):
except:
import traceback
self.errors[au] = traceback.format_exc()
for name, plugin in iteritems(self.app.plugin_manager.get_plugins_by_type('auth')):
for name, plugin in self.app.plugin_manager.get_plugins_by_type('auth').items():
try:
obj = plugin.UserHandler(self.app)
backends.append(obj)
@ -55,7 +54,7 @@ class UserAuthHandler(BUIhandler):
'No backend found for \'{}\':\n{}'.format(self.app.auth,
self.errors)
)
for name, err in iteritems(self.errors):
for name, err in self.errors.items():
self.app.logger.error(
'Unable to load module {}:\n{}'.format(repr(name), err)
)
@ -237,7 +236,7 @@ class UserHandler(BUIuser):
if not self.name:
return
for _, back in iteritems(self.backends):
for _, back in self.backends.items():
user = back.user(self.name)
if not user:
continue
@ -286,7 +285,7 @@ class UserHandler(BUIuser):
"""See :func:`burpui.misc.auth.interface.BUIuser.login`"""
if not self.real:
self.authenticated = False
for name, back in iteritems(self.backends):
for name, back in self.backends.items():
u = back.user(self.name)
if not u:
continue

View file

@ -9,7 +9,6 @@
"""
from flask_login import UserMixin, AnonymousUserMixin
from abc import ABCMeta, abstractmethod, abstractproperty
from six import with_metaclass
import logging
@ -18,7 +17,7 @@ class BUIloader:
logger = logging.getLogger('burp-ui')
class BUIhandler(with_metaclass(ABCMeta, object)):
class BUIhandler(object, metaclass=ABCMeta):
"""The :class:`burpui.misc.auth.interface.BUIhandler` class maintains a list
of ``Burp-UI`` users.
@ -65,7 +64,7 @@ class BUIhandler(with_metaclass(ABCMeta, object)):
return None
class BUIuser(with_metaclass(ABCMeta, UserMixin)):
class BUIuser(UserMixin, metaclass=ABCMeta):
"""The :class:`burpui.misc.auth.interface.BUIuser` class extends the
:class:`flask_login:flask_login.UserMixin` class.
"""

View file

@ -1,5 +1,4 @@
# -*- coding: utf8 -*-
from six import viewitems
from flask_login import AnonymousUserMixin
from .interface import BUIhandler, BUIuser, BUIloader
@ -82,7 +81,7 @@ class LdapLoader(BUIloader):
) or handler.priority
except:
pass
for (opt, key) in viewitems(mapping):
for (opt, key) in mapping.items():
setattr(self, opt, conf.safe_get(key, 'force_string', section=self.section))
if self.validate and self.validate.lower() in ['none', 'optional', 'required']:

View file

@ -17,8 +17,6 @@ import shutil
import subprocess
import tempfile
from six import iteritems, viewkeys
from .interface import BUIbackend
from ..parser.burp1 import Parser
from ...utils import human_readable as _hr, BUIcompress, utc_to_local
@ -471,7 +469,7 @@ class Burp(BUIbackend):
found = False
# this method is not optimal, but it is easy to read and to maintain
for (key, regex) in iteritems(lookup_easy):
for (key, regex) in lookup_easy.items():
reg = re.search(regex, line)
if reg:
found = True
@ -498,7 +496,7 @@ class Burp(BUIbackend):
if found:
continue
for (key, regex) in iteritems(lookup_complex):
for (key, regex) in lookup_complex.items():
reg = re.search(regex, line)
if reg:
# self.logger.debug("match[1]: '{0}'".format(reg.group(1)))
@ -582,7 +580,7 @@ class Burp(BUIbackend):
if 'bytes' not in res:
res['bytes'] = 0
if set(['start', 'estimated_bytes', 'bytes_in']) <= set(viewkeys(res)):
if set(['start', 'estimated_bytes', 'bytes_in']) <= set(res.keys()):
try:
diff = time.time() - int(res['start'])
byteswant = int(res['estimated_bytes'])

View file

@ -16,7 +16,6 @@ import json
import datetime
from select import select
from six import iteritems, viewkeys
from .burp1 import Burp as Burp1
from .interface import BUIbackend
@ -500,7 +499,7 @@ class Burp(Burp1):
backup[name] = counter['count']
else:
backup[name] = {}
for (key, val) in iteritems(counts):
for (key, val) in counts.items():
if val in counter:
backup[name][key] = counter[val]
else:
@ -618,7 +617,7 @@ class Burp(Burp1):
if 'bytes' not in ret:
ret['bytes'] = 0
if set(['time_start', 'estimated_bytes', 'bytes']) <= set(viewkeys(ret)):
if set(['time_start', 'estimated_bytes', 'bytes']) <= set(ret.keys()):
try:
diff = time.time() - int(ret['time_start'])
byteswant = int(ret['estimated_bytes'])

View file

@ -13,8 +13,6 @@ import logging
from abc import ABCMeta, abstractmethod
from six import with_metaclass
G_BURPPORT = 4972
G_BURPHOST = '::1'
G_BURPBIN = '/usr/sbin/burp'
@ -30,7 +28,7 @@ G_ENFORCE = False
G_REVOKE = True
class BUIbackend(with_metaclass(ABCMeta, object)):
class BUIbackend(object, metaclass=ABCMeta):
"""The :class:`burpui.misc.backend.interface.BUIbackend` class provides
a consistent interface backend for any ``burp`` server.

View file

@ -6,7 +6,6 @@ import json
import struct
import traceback
from six import iteritems
from werkzeug.datastructures import ImmutableMultiDict as _ImmutableMultiDict
from .interface import BUIbackend
@ -233,7 +232,7 @@ class Burp(BUIbackend):
pass
else:
res = {}
for name, serv in iteritems(self.servers):
for name, serv in self.servers.items():
try:
res[name] = serv.is_one_backup_running()
except BUIserverException:
@ -248,7 +247,7 @@ class Burp(BUIbackend):
r = {}
for name, serv in iteritems(self.servers):
for name, serv in self.servers.items():
func = getattr(serv, method)
try:
r[name] = func()

View file

@ -11,7 +11,6 @@ import json
import codecs
from glob import glob
from six import iteritems
from .doc import Doc
from .utils import Config
@ -82,7 +81,7 @@ class Parser(Doc):
def clients_conf(self):
if self._clientconfdir_changed():
self._load_conf_clients()
for client, conf in iteritems(self._clients_conf):
for client, conf in self._clients_conf.items():
if conf.changed:
conf.parse(True)
return self._clients_conf

View file

@ -8,12 +8,11 @@
"""
from abc import ABCMeta, abstractmethod
from six import with_metaclass
import logging
class BUIparser(with_metaclass(ABCMeta, object)):
class BUIparser(object, metaclass=ABCMeta):
""":class:`burpui.misc.parser.interface.BUIparser` defines a generic
interface for ``burp`` configuration files parser.
"""

View file

@ -12,7 +12,6 @@ import logging
import subprocess
from hashlib import md5
from six import iteritems
from OpenSSL import crypto
@ -192,7 +191,7 @@ class OSSLConf(object):
dic[key] = val
for key, val in iteritems(dic):
for key, val in dic.items():
self.conf[key] = dic[key] = val = self._translate(dic, key, val)
self.md5 = chksum

View file

@ -15,7 +15,6 @@ from copy import copy
from hashlib import md5
from collections import OrderedDict
from glob import glob
from six import iteritems, viewkeys
from ...utils import NOTIF_ERROR, NOTIF_OK, NOTIF_WARN
from ...security import sanitize_string
@ -542,7 +541,7 @@ class OptionPair(Option, dict):
return []
return self.value[key].parse()
ret = {}
for key, opts in iteritems(self.value):
for key, opts in self.value.items():
ret[key] = opts.parse()
return ret
@ -647,11 +646,11 @@ class File(dict):
@property
def changed(self):
for key, val in iteritems(self.types['include']):
for key, val in self.types['include'].items():
if val.dirty:
self._changed = True
return self._changed
for key, val in iteritems(self.types['template']):
for key, val in self.types['template'].items():
if val.dirty:
self._changed = True
return self._changed
@ -678,7 +677,7 @@ class File(dict):
if ret and not self.dirty:
return ret
ret.clear()
for key, val in iteritems(self.options):
for key, val in self.options.items():
if isinstance(val, OptionMulti) and not raw:
ret.setlist(key, val.parse())
elif isinstance(val, OptionPair) and not raw:
@ -703,7 +702,7 @@ class File(dict):
def clean(self):
self._dirty = False
for _, opt in iteritems(self.options):
for opt in self.options.values():
opt.clean()
def get_name(self):
@ -722,11 +721,11 @@ class File(dict):
'value': opt.parse() if parse else opt,
'reset': opt.get_reset()
}
for key, opt in iteritems(self.types[typ])
for key, opt in self.types[typ].items()
]
ret = OrderedDict()
if typ in self.types:
for key, opt in iteritems(self.types[typ]):
for key, opt in self.types[typ].items():
ret[key] = opt.parse() if parse else opt
return ret
@ -740,7 +739,7 @@ class File(dict):
@property
def dirty(self):
if not self._dirty:
self._dirty = any([x.dirty for _, x in iteritems(self.options)])
self._dirty = any([x.dirty for x in self.options.values()])
return self._dirty
@property
@ -779,10 +778,10 @@ class File(dict):
def _refresh_types(self):
if self._dirty:
for key in viewkeys(self.types):
for key in self.types.keys():
self.types[key] = OrderedDict()
for key, opt in iteritems(self.options):
for key, opt in self.options.items():
if key not in self.associations:
self.types[opt.type][key] = opt
@ -894,9 +893,9 @@ class File(dict):
def __repr__(self):
self._refresh_types()
ret = ''
for key, opts in iteritems(self.types):
for key, opts in self.types.items():
ret += '{} =>\n'.format(key)
for key2, opt in iteritems(opts):
for key2, opt in opts.items():
if key2 in self.associations:
continue
ret += '\t' + repr(opt) + '\n'
@ -904,7 +903,7 @@ class File(dict):
def __str__(self):
ret = ''
for key, val in iteritems(self.options):
for key, val in self.options.items():
if key in self.associations:
continue
tmp = str(val)
@ -973,7 +972,7 @@ class File(dict):
def _dump_resets(self):
ret = {}
for key, val in iteritems(self.options):
for key, val in self.options.items():
resets = val.get_resets()
if resets:
ret[key] = resets
@ -1138,7 +1137,7 @@ class File(dict):
orig = self.raw
oldkeys = [self._get_line_key(x) for x in orig]
newkeys = list(set(viewkeys(data)) - set(oldkeys))
newkeys = list(set(data.keys()) - set(oldkeys))
multi_index_map = {}
pair_index_map = {}
@ -1318,11 +1317,11 @@ class File(dict):
_dump(line, comment=(key in written and not self._line_is_comment(line)))
# write the rest of the multi settings
for key, idx in iteritems(multi_index_map):
for key, idx in multi_index_map.items():
if key not in already_multi and idx < self[key].len():
fil.write('{}\n'.format(self[key].dump(idx)))
# write the rest of the pair settings
for key, idx in iteritems(pair_index_map):
for key, idx in pair_index_map.items():
if key not in already_pair and idx < self[key].len():
fil.wrrite('{}\n'.format(self[key].dump(idx)))
# Write the rest of file inclusions
@ -1435,7 +1434,7 @@ class Config(File):
@property
def changed(self):
for path, conf in iteritems(self.files):
for path, conf in self.files.items():
if conf.changed:
return True
return False
@ -1443,15 +1442,15 @@ class Config(File):
def _parse(self):
orig = self.files.copy()
for root, conf in iteritems(orig):
for root, conf in orig.items():
conf.parse()
for key, val in iteritems(conf.flatten('include', False)):
for key, val in conf.flatten('include', False).items():
for path in val:
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(root), path)
self.add_file(path, root)
self._includes.append(path)
for key, path in iteritems(conf.flatten('template', False)):
for key, path in conf.flatten('template', False).items():
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(root), path)
self.add_file(path, root)
@ -1471,7 +1470,7 @@ class Config(File):
removed = []
orig = self.files
for path, conf in iteritems(orig):
for path, conf in orig.items():
if conf.parent and ((conf.name not in self._includes and
conf.name not in self._templates) or conf.name in removed):
removed.append(path)
@ -1503,31 +1502,31 @@ class Config(File):
# retrieve the offset of the default conf
offset = 0
for idx, (path, _) in enumerate(iteritems(self.files)):
for idx, path in enumerate(self.files.keys()):
if path == dflt.name:
offset = idx
break
for idx, (top, conf) in enumerate(iteritems(self.files)):
for idx, (top, conf) in enumerate(self.files.items()):
if idx < offset:
continue
if idx > offset:
break
node = __new_node(conf.name)
for key, val in iteritems(conf.flatten('include', False)):
for key, val in conf.flatten('include', False).items():
for path in val:
if not os.path.isabs(path):
path = os.path.join(os.path.dirname(top), path)
node['children'].append(__new_node(path, node['full']))
temp[conf.name] = node
self._tree = [x for _, x in iteritems(temp)]
self._tree = [x for x in temp.values()]
return self._tree
def store(self, conf=None, dest=None, insecure=False):
ret = []
if conf and conf in self.files:
return self.files[conf].store(dest, insecure)
for name, conf in iteritems(self.files):
for name, conf in self.files.items():
ret += conf.store(insecure=insecure)
return ret
@ -1536,7 +1535,7 @@ class Config(File):
def clone(self):
cpy = Config(self.name, self.parser, self.mode)
for path, parsed in iteritems(self.files):
for path, parsed in self.files.items():
if path == self.name:
continue
cpy.add_file(path)
@ -1586,24 +1585,24 @@ class Config(File):
def _refresh(self):
if self._dirty or \
any([x.dirty
for _, x in iteritems(self.files)]):
for x in self.files.values()]):
# cleanup "caches"
self.options.clear()
del self.options
self.options = OrderedDict()
for key in viewkeys(self.types):
for key in self.types.keys():
del self.types[key]
self.types[key] = OrderedDict()
# now update caches with new values
for _, fil in iteritems(self.files):
for fil in self.files.values():
self.options.update(fil.options)
self.associations = self.associations.union(fil.associations)
# FIXME: find a way to cache efficiently
# fil.clean()
for key, val in iteritems(self.options):
for key, val in self.options.items():
if key not in self.associations:
self.types[val.type][key] = val
@ -1653,7 +1652,7 @@ class Config(File):
def __repr__(self):
self._refresh()
ret = ''
for key, fil in iteritems(self.files):
for key, fil in self.files.items():
ret += '>' * 5 + key + '<' * 5 + '\n'
ret += repr(fil) + '\n'
return ret.rstrip('\n')

View file

@ -8,7 +8,6 @@
"""
from pluginbase import PluginBase
from six import iteritems
class PluginManager(object):
@ -71,7 +70,7 @@ class PluginManager(object):
def get_plugins_by_type(self, plugin_type):
ret = {}
for name, plugin in iteritems(self.plugins):
for name, plugin in self.plugins.items():
current_type = getattr(plugin, '__type__', None)
if not current_type:
self.app.logger.warning(

View file

@ -11,7 +11,6 @@ import re
import math
import uuid
from six import iteritems
from flask import request, render_template, redirect, url_for, abort, \
flash, Blueprint, session, current_app, g
from flask_login import login_user, login_required, logout_user, current_user
@ -281,7 +280,7 @@ def live_monitor(server=None, name=None):
flash(_('Sorry, there are no running backups'), 'warning')
return redirect(url_for('.home'))
else:
if not any([x for y, x in iteritems(running)]):
if not any([x for y, x in running.items()]):
flash(_('Sorry, there are no running backups'), 'warning')
return redirect(url_for('.home'))

View file

@ -20,7 +20,6 @@ from .plugins import PluginManager
from datetime import timedelta
from flask import Flask
from six import iteritems
BUI_DEFAULTS = {
@ -371,7 +370,7 @@ class BUIServer(Flask):
if self.auth and 'none' not in self.auth:
try:
self.uhandler = UserAuthHandler(self)
for back, err in iteritems(self.uhandler.errors):
for back, err in self.uhandler.errors.items():
self.logger.critical(
'Unable to load \'{}\' authentication backend:\n{}'
.format(back, err)

View file

@ -11,7 +11,6 @@ jQuery/Bootstrap
import sys
import os
from six import iteritems
from flask import current_app
from datetime import timedelta, datetime
from celery.schedules import crontab
@ -137,7 +136,7 @@ def backup_running(self):
if WS_AVAILABLE:
running = False
if isinstance(res, dict):
for _, run in iteritems(res):
for run in res.values():
if len(run) > 0:
running = True
break

View file

@ -9,7 +9,6 @@ WTForms==2.1
arrow==0.12.1
pluginbase==0.5
tzlocal==1.5.1
six==1.11.0
pyOpenSSL>=17.5.0
configobj==5.0.6
pyasn1>=0.2.3

View file

@ -115,7 +115,6 @@ setup(
'gevent',
'arrow==0.12.0',
'tzlocal==1.5.1',
'six==1.11.0',
'pyOpenSSL>=17.5.0',
'configobj==5.0.6',
'pyasn1>=0.2.3',

View file

@ -9,7 +9,6 @@ WTForms==2.1
arrow==0.12.0
pluginbase==0.5
tzlocal==1.5.1
six==1.11.0
pyOpenSSL>=17.5.0
configobj==5.0.6
pyasn1>=0.2.3