本文整理汇总了Python中ansible.module_utils.six.string_types方法的典型用法代码示例。如果您正苦于以下问题:Python six.string_types方法的具体用法?Python six.string_types怎么用?Python six.string_types使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ansible.module_utils.six
的用法示例。
在下文中一共展示了six.string_types方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _is_correct_simple_types
# 需要导入模块: from ansible.module_utils import six [as 别名]
# 或者: from ansible.module_utils.six import string_types [as 别名]
def _is_correct_simple_types(expected_type, value, allow_null=True):
def is_numeric_string(s):
try:
float(s)
return True
except ValueError:
return False
if value is None and allow_null:
return True
elif expected_type == PropType.STRING:
return isinstance(value, string_types)
elif expected_type == PropType.BOOLEAN:
return isinstance(value, bool)
elif expected_type == PropType.INTEGER:
is_integer = isinstance(value, integer_types) and not isinstance(value, bool)
is_digit_string = isinstance(value, string_types) and value.isdigit()
return is_integer or is_digit_string
elif expected_type == PropType.NUMBER:
is_number = isinstance(value, (integer_types, float)) and not isinstance(value, bool)
is_numeric_string = isinstance(value, string_types) and is_numeric_string(value)
return is_number or is_numeric_string
return False
示例2: __init__
# 需要导入模块: from ansible.module_utils import six [as 别名]
# 或者: from ansible.module_utils.six import string_types [as 别名]
def __init__(self, data):
self.msg = None
self.oneview_response = None
if isinstance(data, six.string_types):
self.msg = data
else:
self.oneview_response = data
if data and isinstance(data, dict):
self.msg = data.get('message')
if self.oneview_response:
Exception.__init__(self, self.msg, self.oneview_response)
else:
Exception.__init__(self, self.msg)
示例3: child_to_element
# 需要导入模块: from ansible.module_utils import six [as 别名]
# 或者: from ansible.module_utils.six import string_types [as 别名]
def child_to_element(module, child, in_type):
if in_type == 'xml':
infile = BytesIO(to_bytes(child, errors='surrogate_or_strict'))
try:
parser = etree.XMLParser()
node = etree.parse(infile, parser)
return node.getroot()
except etree.XMLSyntaxError as e:
module.fail_json(msg="Error while parsing child element: %s" % e)
elif in_type == 'yaml':
if isinstance(child, string_types):
return etree.Element(child)
elif isinstance(child, MutableMapping):
if len(child) > 1:
module.fail_json(msg="Can only create children from hashes with one key")
(key, value) = next(iteritems(child))
if isinstance(value, MutableMapping):
children = value.pop('_', None)
node = etree.Element(key, value)
if children is not None:
if not isinstance(children, list):
module.fail_json(msg="Invalid children type: %s, must be list." % type(children))
subnodes = children_to_nodes(module, children)
node.extend(subnodes)
else:
node = etree.Element(key)
node.text = value
return node
else:
module.fail_json(msg="Invalid child type: %s. Children must be either strings or hashes." % type(child))
else:
module.fail_json(msg="Invalid child input type: %s. Type must be either xml or yaml." % in_type)
示例4: _check_validate_data_params
# 需要导入模块: from ansible.module_utils import six [as 别名]
# 或者: from ansible.module_utils.six import string_types [as 别名]
def _check_validate_data_params(self, data, operation_name):
if not operation_name or not isinstance(operation_name, string_types):
raise IllegalArgumentException("The operation_name parameter must be a non-empty string")
if not isinstance(data, dict):
raise IllegalArgumentException("The data parameter must be a dict")
if operation_name not in self._operations:
raise IllegalArgumentException("{0} operation does not support".format(operation_name))
示例5: _check_validate_url_params
# 需要导入模块: from ansible.module_utils import six [as 别名]
# 或者: from ansible.module_utils.six import string_types [as 别名]
def _check_validate_url_params(self, operation, params):
if not operation or not isinstance(operation, string_types):
raise IllegalArgumentException("The operation_name parameter must be a non-empty string")
if not isinstance(params, dict):
raise IllegalArgumentException("The params parameter must be a dict")
if operation not in self._operations:
raise IllegalArgumentException("{0} operation does not support".format(operation))
示例6: tags_match_filters
# 需要导入模块: from ansible.module_utils import six [as 别名]
# 或者: from ansible.module_utils.six import string_types [as 别名]
def tags_match_filters(self, tags):
''' return True if given tags match configured filters '''
if not self.ec2_instance_filters:
return True
for filters in self.ec2_instance_filters:
for filter_name, filter_value in filters.items():
if filter_name[:4] != 'tag:':
continue
filter_name = filter_name[4:]
if filter_name not in tags:
if self.stack_filters:
return False
continue
if isinstance(filter_value, list):
if self.stack_filters and tags[filter_name] not in filter_value:
return False
if not self.stack_filters and tags[filter_name] in filter_value:
return True
if isinstance(filter_value, six.string_types):
if self.stack_filters and tags[filter_name] != filter_value:
return False
if not self.stack_filters and tags[filter_name] == filter_value:
return True
return self.stack_filters
示例7: verify_file
# 需要导入模块: from ansible.module_utils import six [as 别名]
# 或者: from ansible.module_utils.six import string_types [as 别名]
def verify_file(self, host_string):
return isinstance(host_string, string_types)
示例8: _to_lines
# 需要导入模块: from ansible.module_utils import six [as 别名]
# 或者: from ansible.module_utils.six import string_types [as 别名]
def _to_lines(self, stdout):
lines = list()
for item in stdout:
if isinstance(item, string_types):
item = str(item).split('\n')
lines.append(item)
return lines
示例9: _to_lines
# 需要导入模块: from ansible.module_utils import six [as 别名]
# 或者: from ansible.module_utils.six import string_types [as 别名]
def _to_lines(self, stdout):
lines = []
if isinstance(stdout, string_types):
lines = str(stdout).split('\n')
return lines
示例10: to_lines
# 需要导入模块: from ansible.module_utils import six [as 别名]
# 或者: from ansible.module_utils.six import string_types [as 别名]
def to_lines(stdout):
for item in stdout:
if isinstance(item, string_types):
item = str(item).split('\n')
yield item
示例11: normalize_resource_id
# 需要导入模块: from ansible.module_utils import six [as 别名]
# 或者: from ansible.module_utils.six import string_types [as 别名]
def normalize_resource_id(self, value, pattern):
'''
Return a proper resource id string..
:param resource_id: It could be a resource name, resource id or dict containing parts from the pattern.
:param pattern: pattern of resource is, just like in Azure Swagger
'''
value_dict = {}
if isinstance(value, string_types):
value_parts = value.split('/')
if len(value_parts) == 1:
value_dict['name'] = value
else:
pattern_parts = pattern.split('/')
if len(value_parts) != len(pattern_parts):
return None
for i in range(len(value_parts)):
if pattern_parts[i].startswith('{'):
value_dict[pattern_parts[i][1:-1]] = value_parts[i]
elif value_parts[i].lower() != pattern_parts[i].lower():
return None
elif isinstance(value, dict):
value_dict = value
else:
return None
if not value_dict.get('subscription_id'):
value_dict['subscription_id'] = self.subscription_id
if not value_dict.get('resource_group'):
value_dict['resource_group'] = self.resource_group
# check if any extra values passed
for k in value_dict:
if not ('{' + k + '}') in pattern:
return None
# format url
return pattern.format(**value_dict)
示例12: serialize_spec
# 需要导入模块: from ansible.module_utils import six [as 别名]
# 或者: from ansible.module_utils.six import string_types [as 别名]
def serialize_spec(clonespec):
"""Serialize a clonespec or a relocation spec"""
data = {}
attrs = dir(clonespec)
attrs = [x for x in attrs if not x.startswith('_')]
for x in attrs:
xo = getattr(clonespec, x)
if callable(xo):
continue
xt = type(xo)
if xo is None:
data[x] = None
elif isinstance(xo, vim.vm.ConfigSpec):
data[x] = serialize_spec(xo)
elif isinstance(xo, vim.vm.RelocateSpec):
data[x] = serialize_spec(xo)
elif isinstance(xo, vim.vm.device.VirtualDisk):
data[x] = serialize_spec(xo)
elif isinstance(xo, vim.vm.device.VirtualDeviceSpec.FileOperation):
data[x] = to_text(xo)
elif isinstance(xo, vim.Description):
data[x] = {
'dynamicProperty': serialize_spec(xo.dynamicProperty),
'dynamicType': serialize_spec(xo.dynamicType),
'label': serialize_spec(xo.label),
'summary': serialize_spec(xo.summary),
}
elif hasattr(xo, 'name'):
data[x] = to_text(xo) + ':' + to_text(xo.name)
elif isinstance(xo, vim.vm.ProfileSpec):
pass
elif issubclass(xt, list):
data[x] = []
for xe in xo:
data[x].append(serialize_spec(xe))
elif issubclass(xt, string_types + integer_types + (float, bool)):
if issubclass(xt, integer_types):
data[x] = int(xo)
else:
data[x] = to_text(xo)
elif issubclass(xt, bool):
data[x] = xo
elif issubclass(xt, dict):
data[to_text(x)] = {}
for k, v in xo.items():
k = to_text(k)
data[x][k] = serialize_spec(v)
else:
data[x] = str(xt)
return data
示例13: __init__
# 需要导入模块: from ansible.module_utils import six [as 别名]
# 或者: from ansible.module_utils.six import string_types [as 别名]
def __init__(self, **kwargs):
self.entity_key = kwargs.pop('entity_key', 'name')
self.entity_name = kwargs.pop('entity_name', self.entity_name_from_class)
entity_opts = kwargs.pop('entity_opts', {})
super(ForemanStatelessEntityAnsibleModule, self).__init__(**kwargs)
if 'resource_type' not in entity_opts:
entity_opts['resource_type'] = inflector.pluralize(self.entity_name)
if 'thin' not in entity_opts:
# Explicit None to trigger the _thin_default mechanism lazily
entity_opts['thin'] = None
if 'failsafe' not in entity_opts:
entity_opts['failsafe'] = True
if 'search_operator' not in entity_opts:
entity_opts['search_operator'] = '='
if 'search_by' not in entity_opts:
entity_opts['search_by'] = ENTITY_KEYS.get(entity_opts['resource_type'], 'name')
self.foreman_spec.update(_foreman_spec_helper(dict(
entity=dict(
type='entity',
flat_name='id',
ensure=False,
**entity_opts
),
))[0])
if 'parent' in self.foreman_spec and self.foreman_spec['parent'].get('type') == 'entity':
if 'resouce_type' not in self.foreman_spec['parent']:
self.foreman_spec['parent']['resource_type'] = self.foreman_spec['entity']['resource_type']
current, parent = split_fqn(self.foreman_params[self.entity_key])
if isinstance(self.foreman_params.get('parent'), six.string_types):
if parent:
self.fail_json(msg="Please specify the parent either separately, or as part of the title.")
parent = self.foreman_params['parent']
elif parent:
self.foreman_params['parent'] = parent
self.foreman_params[self.entity_key] = current
self.foreman_params['entity'] = build_fqn(current, parent)
else:
self.foreman_params['entity'] = self.foreman_params.get(self.entity_key)
示例14: get_host_info_dict_from_instance
# 需要导入模块: from ansible.module_utils import six [as 别名]
# 或者: from ansible.module_utils.six import string_types [as 别名]
def get_host_info_dict_from_instance(self, instance):
instance_vars = {}
for key in vars(instance):
value = getattr(instance, key)
key = self.to_safe('ec2_' + key)
# Handle complex types
# state/previous_state changed to properties in boto in https://github.com/boto/boto/commit/a23c379837f698212252720d2af8dec0325c9518
if key == 'ec2__state':
instance_vars['ec2_state'] = instance.state or ''
instance_vars['ec2_state_code'] = instance.state_code
elif key == 'ec2__previous_state':
instance_vars['ec2_previous_state'] = instance.previous_state or ''
instance_vars['ec2_previous_state_code'] = instance.previous_state_code
elif isinstance(value, (int, bool)):
instance_vars[key] = value
elif isinstance(value, six.string_types):
instance_vars[key] = value.strip()
elif value is None:
instance_vars[key] = ''
elif key == 'ec2_region':
instance_vars[key] = value.name
elif key == 'ec2__placement':
instance_vars['ec2_placement'] = value.zone
elif key == 'ec2_tags':
for k, v in value.items():
if self.expand_csv_tags and ',' in v:
v = list(map(lambda x: x.strip(), v.split(',')))
key = self.to_safe('ec2_tag_' + k)
instance_vars[key] = v
elif key == 'ec2_groups':
group_ids = []
group_names = []
for group in value:
group_ids.append(group.id)
group_names.append(group.name)
instance_vars["ec2_security_group_ids"] = ','.join([str(i) for i in group_ids])
instance_vars["ec2_security_group_names"] = ','.join([str(i) for i in group_names])
elif key == 'ec2_block_device_mapping':
instance_vars["ec2_block_devices"] = {}
for k, v in value.items():
instance_vars["ec2_block_devices"][os.path.basename(k)] = v.volume_id
else:
pass
# TODO Product codes if someone finds them useful
# print key
# print type(value)
# print value
instance_vars[self.to_safe('ec2_account_id')] = self.aws_account_id
return instance_vars
示例15: display
# 需要导入模块: from ansible.module_utils import six [as 别名]
# 或者: from ansible.module_utils.six import string_types [as 别名]
def display(obj, result):
msg = ''
result = result._result
display = obj._display.display
wrap_width = 77
first = obj.first_host and obj.first_item
# Only display msg if debug module or if failed (some modules have undesired 'msg' on 'ok')
if 'msg' in result and (obj.task_failed or obj.action == 'debug'):
msg = result.pop('msg', '')
# Disable Ansible's verbose setting for debug module to avoid the CallbackBase._dump_results()
if '_ansible_verbose_always' in result:
del result['_ansible_verbose_always']
# Display additional info when failed
if obj.task_failed:
items = (item for item in ['reason', 'module_stderr', 'module_stdout', 'stderr'] if item in result and to_text(result[item]) != '')
for item in items:
msg = result[item] if msg == '' else '\n'.join([msg, result.pop(item, '')])
# Add blank line between this fail message and the json dump Ansible displays next
msg = '\n'.join([msg, ''])
# Must pass unicode strings to Display.display() to prevent UnicodeError tracebacks
if isinstance(msg, list):
msg = '\n'.join([to_text(x) for x in msg])
elif not isinstance(msg, string_types):
msg = to_text(msg)
# Wrap text
msg = '\n'.join([textwrap.fill(line, wrap_width, replace_whitespace=False)
for line in msg.splitlines()])
# Display system info and msg, with horizontal rule between hosts/items
hr = '-' * int(wrap_width*.67)
if obj.task_failed and first:
display(system(obj.vagrant_version), 'bright gray')
display(hr, 'bright gray')
if msg == '':
if obj.task_failed and not first:
display(hr, 'bright gray')
else:
return
else:
if not first:
display(hr, 'bright gray')
display(msg, 'red' if obj.task_failed else 'bright purple')