Fix dict related issues for Python 2/3 compatible code

Story: 2003430
Task: 26353

Change-Id: Ic673136ece7f0a16177cc6a96377456d127e55bf
Signed-off-by: Sun Austin <austin.sun@intel.com>
This commit is contained in:
Sun Austin 2018-09-18 13:28:31 +08:00
parent 3ee0e68559
commit 5c0dcd6e4c
19 changed files with 31 additions and 31 deletions

View File

@ -54,7 +54,7 @@ class Nodes(base.APIBase):
"A list containing a self link and associated nodes links" "A list containing a self link and associated nodes links"
def __init__(self, **kwargs): def __init__(self, **kwargs):
self.fields = objects.sm_node.fields.keys() self.fields = list(objects.sm_node.fields)
for k in self.fields: for k in self.fields:
setattr(self, k, kwargs.get(k)) setattr(self, k, kwargs.get(k))

View File

@ -59,7 +59,7 @@ class ServiceGroup(base.APIBase):
"A list containing a self link and associated sm_sda links" "A list containing a self link and associated sm_sda links"
def __init__(self, **kwargs): def __init__(self, **kwargs):
self.fields = objects.sm_sda.fields.keys() self.fields = list(objects.sm_sda.fields)
for k in self.fields: for k in self.fields:
setattr(self, k, kwargs.get(k)) setattr(self, k, kwargs.get(k))

View File

@ -135,7 +135,7 @@ def rest_api_request(token, method, api_cmd, api_cmd_headers=None,
request_info.add_header("Accept", "application/json") request_info.add_header("Accept", "application/json")
if api_cmd_headers is not None: if api_cmd_headers is not None:
for header_type, header_value in api_cmd_headers.items(): for header_type, header_value in list(api_cmd_headers.items()):
request_info.add_header(header_type, header_value) request_info.add_header(header_type, header_value)
if api_cmd_payload is not None: if api_cmd_payload is not None:
@ -484,7 +484,7 @@ class ServiceNodeController(rest.RestController):
chk_list[sda.service_group_name].remove(service_name) chk_list[sda.service_group_name].remove(service_name)
all_good = True all_good = True
for svcs in chk_list.values(): for svcs in list(chk_list.values()):
if len(svcs) > 0: if len(svcs) > 0:
all_good = False all_good = False
break break

View File

@ -55,7 +55,7 @@ class Services(base.APIBase):
"A list containing a self link and associated services links" "A list containing a self link and associated services links"
def __init__(self, **kwargs): def __init__(self, **kwargs):
self.fields = objects.service.fields.keys() self.fields = list(objects.service.fields)
for k in self.fields: for k in self.fields:
setattr(self, k, kwargs.get(k)) setattr(self, k, kwargs.get(k))

View File

@ -59,7 +59,7 @@ class SmSda(base.APIBase):
"A list containing a self link and associated sm_sda links" "A list containing a self link and associated sm_sda links"
def __init__(self, **kwargs): def __init__(self, **kwargs):
self.fields = objects.sm_sda.fields.keys() self.fields = list(objects.sm_sda.fields)
for k in self.fields: for k in self.fields:
setattr(self, k, kwargs.get(k)) setattr(self, k, kwargs.get(k))

View File

@ -73,7 +73,7 @@ class ProcessExecutionError(IOError):
def _cleanse_dict(original): def _cleanse_dict(original):
"""Strip all admin_password, new_pass, rescue_pass keys from a dict.""" """Strip all admin_password, new_pass, rescue_pass keys from a dict."""
return dict((k, v) for k, v in original.iteritems() if not "_pass" in k) return dict((k, v) for k, v in original.items() if not "_pass" in k)
def wrap_exception(notifier=None, publisher_id=None, event_type=None, def wrap_exception(notifier=None, publisher_id=None, event_type=None,
@ -146,7 +146,7 @@ class SmApiException(Exception):
# kwargs doesn't match a variable in the message # kwargs doesn't match a variable in the message
# log the issue and the kwargs # log the issue and the kwargs
LOG.exception(_('Exception in string format operation')) LOG.exception(_('Exception in string format operation'))
for name, value in kwargs.iteritems(): for name, value in kwargs.items():
LOG.error("%s: %s" % (name, value)) LOG.error("%s: %s" % (name, value))
if CONF.fatal_exception_format_errors: if CONF.fatal_exception_format_errors:

View File

@ -39,7 +39,7 @@ def get_attrname(name):
def make_class_properties(cls): def make_class_properties(cls):
# NOTE(danms): Inherit Sm_apiObject's base fields only # NOTE(danms): Inherit Sm_apiObject's base fields only
cls.fields.update(Sm_apiObject.fields) cls.fields.update(Sm_apiObject.fields)
for name, typefn in cls.fields.iteritems(): for name, typefn in cls.fields.items():
def getter(self, name=name): def getter(self, name=name):
attrname = get_attrname(name) attrname = get_attrname(name)
@ -120,7 +120,7 @@ def remotable(fn):
if Sm_apiObject.indirection_api: if Sm_apiObject.indirection_api:
updates, result = Sm_apiObject.indirection_api.object_action( updates, result = Sm_apiObject.indirection_api.object_action(
ctxt, self, fn.__name__, args, kwargs) ctxt, self, fn.__name__, args, kwargs)
for key, value in updates.iteritems(): for key, value in updates.items():
if key in self.fields: if key in self.fields:
self[key] = self._attr_from_primitive(key, value) self[key] = self._attr_from_primitive(key, value)
self._changed_fields = set(updates.get('obj_what_changed', [])) self._changed_fields = set(updates.get('obj_what_changed', []))
@ -336,7 +336,7 @@ class Sm_apiObject(object):
name in self.obj_extra_fields): name in self.obj_extra_fields):
yield name, getattr(self, name) yield name, getattr(self, name)
items = lambda self: list(self.iteritems()) items = lambda self: list(self.items())
def __getitem__(self, name): def __getitem__(self, name):
"""For backwards-compatibility with dict-based objects. """For backwards-compatibility with dict-based objects.
@ -383,7 +383,7 @@ class Sm_apiObject(object):
def get_defaults(cls): def get_defaults(cls):
"""Return a dict of its fields with their default value.""" """Return a dict of its fields with their default value."""
return dict((k, v(None)) return dict((k, v(None))
for k, v in cls.fields.iteritems() for k, v in cls.fields.items()
if k != "id" and callable(v)) if k != "id" and callable(v))
@ -497,7 +497,7 @@ def obj_to_primitive(obj):
return [obj_to_primitive(x) for x in obj] return [obj_to_primitive(x) for x in obj]
elif isinstance(obj, Sm_apiObject): elif isinstance(obj, Sm_apiObject):
result = {} result = {}
for key, value in obj.iteritems(): for key, value in obj.items():
result[key] = obj_to_primitive(value) result[key] = obj_to_primitive(value)
return result return result
else: else:

View File

@ -64,7 +64,7 @@ class ModelBase(object):
return getattr(self, key, default) return getattr(self, key, default)
def __iter__(self): def __iter__(self):
columns = dict(object_mapper(self).columns).keys() columns = list(dict(object_mapper(self).columns))
# NOTE(russellb): Allow models to specify other keys that can be looked # NOTE(russellb): Allow models to specify other keys that can be looked
# up, beyond the actual db columns. An example would be the 'name' # up, beyond the actual db columns. An example would be the 'name'
# property for an Instance. # property for an Instance.
@ -79,7 +79,7 @@ class ModelBase(object):
def update(self, values): def update(self, values):
"""Make the model object behave like a dict.""" """Make the model object behave like a dict."""
for k, v in values.iteritems(): for k, v in values.items():
setattr(self, k, v) setattr(self, k, v)
def iteritems(self): def iteritems(self):
@ -87,10 +87,10 @@ class ModelBase(object):
Includes attributes from joins.""" Includes attributes from joins."""
local = dict(self) local = dict(self)
joined = dict([(k, v) for k, v in self.__dict__.iteritems() joined = dict([(k, v) for k, v in self.__dict__.items()
if not k[0] == '_']) if not k[0] == '_'])
local.update(joined) local.update(joined)
return local.iteritems() return iter(local.items())
class TimestampMixin(object): class TimestampMixin(object):

View File

@ -121,7 +121,7 @@ def to_primitive(value, convert_instances=False, convert_datetime=True,
level=level, level=level,
max_depth=max_depth) max_depth=max_depth)
if isinstance(value, dict): if isinstance(value, dict):
return dict((k, recursive(v)) for k, v in value.iteritems()) return dict((k, recursive(v)) for k, v in value.items())
elif isinstance(value, (list, tuple)): elif isinstance(value, (list, tuple)):
return [recursive(lv) for lv in value] return [recursive(lv) for lv in value]
@ -134,7 +134,7 @@ def to_primitive(value, convert_instances=False, convert_datetime=True,
if convert_datetime and isinstance(value, datetime.datetime): if convert_datetime and isinstance(value, datetime.datetime):
return timeutils.strtime(value) return timeutils.strtime(value)
elif hasattr(value, 'iteritems'): elif hasattr(value, 'iteritems'):
return recursive(dict(value.iteritems()), level=level + 1) return recursive(dict(iter(value.items())), level=level + 1)
elif hasattr(value, '__iter__'): elif hasattr(value, '__iter__'):
return recursive(list(value)) return recursive(list(value))
elif convert_instances and hasattr(value, '__dict__'): elif convert_instances and hasattr(value, '__dict__'):

View File

@ -380,7 +380,7 @@ def _find_facility_from_conf():
facility = facility_names.get(CONF.syslog_log_facility) facility = facility_names.get(CONF.syslog_log_facility)
if facility is None: if facility is None:
valid_facilities = facility_names.keys() valid_facilities = list(facility_names)
consts = ['LOG_AUTH', 'LOG_AUTHPRIV', 'LOG_CRON', 'LOG_DAEMON', consts = ['LOG_AUTH', 'LOG_AUTHPRIV', 'LOG_CRON', 'LOG_DAEMON',
'LOG_FTP', 'LOG_KERN', 'LOG_LPR', 'LOG_MAIL', 'LOG_NEWS', 'LOG_FTP', 'LOG_KERN', 'LOG_LPR', 'LOG_MAIL', 'LOG_NEWS',
'LOG_AUTH', 'LOG_SYSLOG', 'LOG_USER', 'LOG_UUCP', 'LOG_AUTH', 'LOG_SYSLOG', 'LOG_USER', 'LOG_UUCP',

View File

@ -159,7 +159,7 @@ def _get_drivers():
for notification_driver in CONF.notification_driver: for notification_driver in CONF.notification_driver:
add_driver(notification_driver) add_driver(notification_driver)
return _drivers.values() return list(_drivers.values())
def add_driver(notification_driver): def add_driver(notification_driver):

View File

@ -240,7 +240,7 @@ def msg_reply(conf, msg_id, reply_q, connection_pool, reply=None,
msg = {'result': reply, 'failure': failure} msg = {'result': reply, 'failure': failure}
except TypeError: except TypeError:
msg = {'result': dict((k, repr(v)) msg = {'result': dict((k, repr(v))
for k, v in reply.__dict__.iteritems()), for k, v in reply.__dict__.items()),
'failure': failure} 'failure': failure}
if ending: if ending:
msg['ending'] = True msg['ending'] = True
@ -307,7 +307,7 @@ def pack_context(msg, context):
""" """
context_d = dict([('_context_%s' % key, value) context_d = dict([('_context_%s' % key, value)
for (key, value) in context.to_dict().iteritems()]) for (key, value) in context.to_dict().items()])
msg.update(context_d) msg.update(context_d)

View File

@ -89,7 +89,7 @@ class RPCException(Exception):
# kwargs doesn't match a variable in the message # kwargs doesn't match a variable in the message
# log the issue and the kwargs # log the issue and the kwargs
LOG.exception(_('Exception in string format operation')) LOG.exception(_('Exception in string format operation'))
for name, value in kwargs.iteritems(): for name, value in kwargs.items():
LOG.error("%s: %s" % (name, value)) LOG.error("%s: %s" % (name, value))
# at least get the core message out if something happened # at least get the core message out if something happened
message = self.message message = self.message

View File

@ -125,7 +125,7 @@ class RpcDispatcher(object):
:returns: A new set of deserialized args :returns: A new set of deserialized args
""" """
new_kwargs = dict() new_kwargs = dict()
for argname, arg in kwargs.iteritems(): for argname, arg in kwargs.items():
new_kwargs[argname] = self.serializer.deserialize_entity(context, new_kwargs[argname] = self.serializer.deserialize_entity(context,
arg) arg)
return new_kwargs return new_kwargs

View File

@ -432,7 +432,7 @@ class Connection(object):
'virtual_host': self.conf.rabbit_virtual_host, 'virtual_host': self.conf.rabbit_virtual_host,
} }
for sp_key, value in server_params.iteritems(): for sp_key, value in server_params.items():
p_key = server_params_to_kombu_params.get(sp_key, sp_key) p_key = server_params_to_kombu_params.get(sp_key, sp_key)
params[p_key] = value params[p_key] = value

View File

@ -368,7 +368,7 @@ class Connection(object):
consumers = self.consumers consumers = self.consumers
self.consumers = {} self.consumers = {}
for consumer in consumers.itervalues(): for consumer in consumers.values():
consumer.reconnect(self.session) consumer.reconnect(self.session)
self._register_consumer(consumer) self._register_consumer(consumer)

View File

@ -99,7 +99,7 @@ class RpcProxy(object):
:returns: A new set of serialized arguments :returns: A new set of serialized arguments
""" """
new_kwargs = dict() new_kwargs = dict()
for argname, arg in kwargs.iteritems(): for argname, arg in kwargs.items():
new_kwargs[argname] = self.serializer.serialize_entity(context, new_kwargs[argname] = self.serializer.serialize_entity(context,
arg) arg)
return new_kwargs return new_kwargs

View File

@ -58,7 +58,7 @@ def canonicalize_emails(changelog, mapping):
"""Takes in a string and an email alias mapping and replaces all """Takes in a string and an email alias mapping and replaces all
instances of the aliases in the string with their real email. instances of the aliases in the string with their real email.
""" """
for alias, email_address in mapping.iteritems(): for alias, email_address in mapping.items():
changelog = changelog.replace(alias, email_address) changelog = changelog.replace(alias, email_address)
return changelog return changelog
@ -245,7 +245,7 @@ def get_cmdclass():
for pkg in self.distribution.packages: for pkg in self.distribution.packages:
if '.' not in pkg: if '.' not in pkg:
os.path.walk(pkg, _find_modules, modules) os.path.walk(pkg, _find_modules, modules)
module_list = modules.keys() module_list = list(modules.keys())
module_list.sort() module_list.sort()
autoindex_filename = os.path.join(source_dir, 'autoindex.rst') autoindex_filename = os.path.join(source_dir, 'autoindex.rst')
with open(autoindex_filename, 'w') as autoindex: with open(autoindex_filename, 'w') as autoindex:

View File

@ -99,7 +99,7 @@ class Resource(object):
self._loaded = loaded self._loaded = loaded
def _add_details(self, info): def _add_details(self, info):
for (k, v) in info.iteritems(): for (k, v) in info.items():
setattr(self, k, v) setattr(self, k, v)
def __getattr__(self, k): def __getattr__(self, k):