Merge "Add default namespace to apiclient"

This commit is contained in:
Jenkins 2016-01-12 10:46:09 +00:00 committed by Gerrit Code Review
commit 01f67dcaf5
2 changed files with 80 additions and 0 deletions

View File

@ -30,6 +30,7 @@ from jobs import JobManager
from actions import ActionManager
from sessions import SessionManager
from oslo_config import cfg
from freezer.utils import Namespace
CONF = cfg.CONF
@ -195,6 +196,10 @@ class Client(object):
verify=True):
self.opts = opts
# this creates a namespace for self.opts when the client is
# created from other method rather than command line arguments.
if self.opts is None:
self.opts = Namespace({})
if token:
self.opts.os_token = token
if username:

View File

@ -28,6 +28,8 @@ import sys
from functools import wraps
from collections import Mapping, Sequence
class OpenstackOptions:
"""
@ -442,3 +444,76 @@ def delete_file(path_to_file):
os.remove(path_to_file)
except Exception:
logging.warning("Error deleting file {0}".format(path_to_file))
class Namespace(dict):
"""A dict subclass that exposes its items as attributes.
Warning: Namespace instances do not have direct access to the
dict methods.
"""
def __init__(self, obj={}):
super(Namespace, self).__init__(obj)
def __dir__(self):
return tuple(self)
def __repr__(self):
return "%s(%s)" % (type(self).__name__,
super(Namespace, self).__repr__())
def __getattribute__(self, name):
try:
return self[name]
except KeyError:
# Return None in case the value doesn't exists
# this is not an issue for the apiclient because it skips
# None values
return None
def __setattr__(self, name, value):
self[name] = value
def __delattr__(self, name):
del self[name]
@classmethod
def from_object(cls, obj, names=None):
if names is None:
names = dir(obj)
ns = {name:getattr(obj, name) for name in names}
return cls(ns)
@classmethod
def from_mapping(cls, ns, names=None):
if names:
ns = {name: ns[name] for name in names}
return cls(ns)
@classmethod
def from_sequence(cls, seq, names=None):
if names:
seq = {name: val for name, val in seq if name in names}
return cls(seq)
@staticmethod
def hasattr(ns, name):
try:
object.__getattribute__(ns, name)
except AttributeError:
return False
return True
@staticmethod
def getattr(ns, name):
return object.__getattribute__(ns, name)
@staticmethod
def setattr(ns, name, value):
return object.__setattr__(ns, name, value)
@staticmethod
def delattr(ns, name):
return object.__delattr__(ns, name)