本文整理汇总了Python中toscaparser.utils.gettextutils._函数的典型用法代码示例。如果您正苦于以下问题:Python _函数的具体用法?Python _怎么用?Python _使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了_函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _find_node_template
def _find_node_template(self, node_template_name):
if node_template_name == TARGET:
if not isinstance(self.context.type_definition, RelationshipType):
ExceptionCollector.appendException(
KeyError(_('"TARGET" keyword can only be used in context'
' to "Relationships" target node')))
return
return self.context.target
if node_template_name == SOURCE:
if not isinstance(self.context.type_definition, RelationshipType):
ExceptionCollector.appendException(
KeyError(_('"SOURCE" keyword can only be used in context'
' to "Relationships" source node')))
return
return self.context.source
name = self.context.name \
if node_template_name == SELF and \
not isinstance(self.context, list) \
else node_template_name
for node_template in self.tosca_tpl.nodetemplates:
if node_template.name == name:
return node_template
ExceptionCollector.appendException(
KeyError(_(
'Node template "{0}" was not found.'
).format(node_template_name)))
示例2: _validate_external_reference
def _validate_external_reference(self, tpl_file, resource_file,
raise_exc=True):
"""Verify that the external resource exists
If resource_file is a URL verify that the URL is valid.
If resource_file is a relative path verify that the path is valid
considering base folder (self.temp_dir) and tpl_file.
Note that in a CSAR resource_file cannot be an absolute path.
"""
if UrlUtils.validate_url(resource_file):
msg = (_('The resource at "%s" cannot be accessed.') %
resource_file)
try:
if UrlUtils.url_accessible(resource_file):
return
else:
ExceptionCollector.appendException(
URLException(what=msg))
self.error_caught = True
except Exception:
ExceptionCollector.appendException(
URLException(what=msg))
self.error_caught = True
if os.path.isfile(os.path.join(self.temp_dir,
os.path.dirname(tpl_file),
resource_file)):
return
if raise_exc:
ExceptionCollector.appendException(
ValueError(_('The resource "%s" does not exist.')
% resource_file))
self.error_caught = True
示例3: validate
def validate(self):
if len(self.args) < 2:
ExceptionCollector.appendException(
ValueError(_('Illegal arguments for function "{0}". Expected '
'arguments: "node-template-name", "req-or-cap"'
'(optional), "property name"'
).format(GET_ATTRIBUTE)))
return
elif len(self.args) == 2:
self._find_node_template_containing_attribute()
else:
node_tpl = self._find_node_template(self.args[0])
if node_tpl is None:
return
index = 2
attrs = node_tpl.type_definition.get_attributes_def()
found = [attrs[self.args[1]]] if self.args[1] in attrs else []
if found:
attr = found[0]
else:
index = 3
# then check the req or caps
attr = self._find_req_or_cap_attribute(self.args[1],
self.args[2])
value_type = attr.schema['type']
if len(self.args) > index:
for elem in self.args[index:]:
if value_type == "list":
if not isinstance(elem, int):
ExceptionCollector.appendException(
ValueError(_('Illegal arguments for function'
' "{0}". "{1}" Expected positive'
' integer argument'
).format(GET_ATTRIBUTE, elem)))
value_type = attr.schema['entry_schema']['type']
elif value_type == "map":
value_type = attr.schema['entry_schema']['type']
elif value_type in Schema.PROPERTY_TYPES:
ExceptionCollector.appendException(
ValueError(_('Illegal arguments for function'
' "{0}". Unexpected attribute/'
'index value "{1}"'
).format(GET_ATTRIBUTE, elem)))
return
else: # It is a complex type
data_type = DataType(value_type)
props = data_type.get_all_properties()
found = [props[elem]] if elem in props else []
if found:
prop = found[0]
value_type = prop.schema['type']
else:
ExceptionCollector.appendException(
KeyError(_('Illegal arguments for function'
' "{0}". Attribute name "{1}" not'
' found in "{2}"'
).format(GET_ATTRIBUTE,
elem,
value_type)))
示例4: convert_unit_size_to_num
def convert_unit_size_to_num(size, unit=None):
"""Convert given size to a number representing given unit.
If unit is None, convert to a number representing UNIT_SIZE_DEFAULT
:param size: unit size e.g. 1 TB
:param unit: unit to be converted to e.g GB
:return: converted number e.g. 1000 for 1 TB size and unit GB
"""
if unit:
unit = MemoryUnit.validate_unit(unit)
else:
unit = MemoryUnit.UNIT_SIZE_DEFAULT
log.info(_('A memory unit is not provided for size; using the '
'default unit %(default)s.') % {'default': 'B'})
regex = re.compile('(\d*)\s*(\w*)')
result = regex.match(str(size)).groups()
if result[1]:
unit_size = MemoryUnit.validate_unit(result[1])
converted = int(str_to_num(result[0])
* MemoryUnit.UNIT_SIZE_DICT[unit_size]
* math.pow(MemoryUnit.UNIT_SIZE_DICT
[unit], -1))
log.info(_('Given size %(size)s is converted to %(num)s '
'%(unit)s.') % {'size': size,
'num': converted, 'unit': unit})
else:
converted = (str_to_num(result[0]))
return converted
示例5: _find_node_template
def _find_node_template(self, node_template_name):
if node_template_name == SELF:
return self.context
# enable the HOST value in the function
if node_template_name == HOST:
return self._find_host_containing_property()
if node_template_name == TARGET:
if not isinstance(self.context.type_definition, RelationshipType):
ExceptionCollector.appendException(
KeyError(_('"TARGET" keyword can only be used in context'
' to "Relationships" target node')))
return
return self.context.target
if node_template_name == SOURCE:
if not isinstance(self.context.type_definition, RelationshipType):
ExceptionCollector.appendException(
KeyError(_('"SOURCE" keyword can only be used in context'
' to "Relationships" source node')))
return
return self.context.source
if not hasattr(self.tosca_tpl, 'nodetemplates'):
return
for node_template in self.tosca_tpl.nodetemplates:
if node_template.name == node_template_name:
return node_template
ExceptionCollector.appendException(
KeyError(_(
'Node template "{0}" was not found.'
).format(node_template_name)))
示例6: _get_capability_attribute
def _get_capability_attribute(self,
node_template,
capability_name,
attr_name):
"""Gets a node template capability attribute."""
caps = node_template.get_capabilities()
if caps and capability_name in caps.keys():
cap = caps[capability_name]
attribute = None
attrs = cap.definition.get_attributes_def()
if attrs and attr_name in attrs.keys():
attribute = attrs[attr_name]
if not attribute:
ExceptionCollector.appendException(
KeyError(_('Attribute "%(attr)s" was not found in '
'capability "%(cap)s" of node template '
'"%(ntpl1)s" referenced from node template '
'"%(ntpl2)s".') % {'attr': attr_name,
'cap': capability_name,
'ntpl1': node_template.name,
'ntpl2': self.context.name}))
return attribute
msg = _('Requirement/Capability "{0}" referenced from node template '
'"{1}" was not found in node template "{2}".').format(
capability_name,
self.context.name,
node_template.name)
ExceptionCollector.appendException(KeyError(msg))
示例7: _get_capability_property
def _get_capability_property(self,
node_template,
capability_name,
property_name):
"""Gets a node template capability property."""
caps = node_template.get_capabilities()
if caps and capability_name in caps.keys():
cap = caps[capability_name]
property = None
props = cap.get_properties()
if props and property_name in props.keys():
property = props[property_name].value
if not property:
ExceptionCollector.appendException(
KeyError(_('Property "%(prop)s" was not found in '
'capability "%(cap)s" of node template '
'"%(ntpl1)s" referenced from node template '
'"%(ntpl2)s".') % {'prop': property_name,
'cap': capability_name,
'ntpl1': node_template.name,
'ntpl2': self.context.name}))
return property
msg = _('Requirement/Capability "{0}" referenced from node template '
'"{1}" was not found in node template "{2}".').format(
capability_name,
self.context.name,
node_template.name)
ExceptionCollector.appendException(KeyError(msg))
示例8: test_invalid_section_names
def test_invalid_section_names(self):
tosca_tpl = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"data/test_invalid_section_names.yaml")
self.assertRaises(exception.ValidationError, ToscaTemplate, tosca_tpl,
None)
err1_msg = _('Template contains unknown field '
'"tosca_definitions_versions". Refer to the definition '
'to verify valid values.')
exception.ExceptionCollector.assertExceptionMessage(
exception.UnknownFieldError, err1_msg)
err2_msg = _('Template contains unknown field "descriptions". '
'Refer to the definition to verify valid values.')
exception.ExceptionCollector.assertExceptionMessage(
exception.UnknownFieldError, err2_msg)
err3_msg = _('Template contains unknown field "import". Refer to '
'the definition to verify valid values.')
exception.ExceptionCollector.assertExceptionMessage(
exception.UnknownFieldError, err3_msg)
err4_msg = _('Template contains unknown field "topology_templates". '
'Refer to the definition to verify valid values.')
exception.ExceptionCollector.assertExceptionMessage(
exception.UnknownFieldError, err4_msg)
示例9: test_constraint_for_scalar_unit
def test_constraint_for_scalar_unit(self):
tpl_snippet = '''
server:
type: tosca.my.nodes.Compute
properties:
cpu_frequency: 0.05 GHz
disk_size: 500 MB
mem_size: 1 MB
'''
nodetemplates = yamlparser.simple_parse(tpl_snippet)
nodetemplate = NodeTemplate('server', nodetemplates, self.custom_def)
props = nodetemplate.get_properties()
if 'cpu_frequency' in props.keys():
error = self.assertRaises(exception.ValidationError,
props['cpu_frequency'].validate)
self.assertEqual(_('The value "0.05 GHz" of property '
'"cpu_frequency" must be greater than or equal '
'to "0.1 GHz".'), error.__str__())
if 'disk_size' in props.keys():
error = self.assertRaises(exception.ValidationError,
props['disk_size'].validate)
self.assertEqual(_('The value "500 MB" of property "disk_size" '
'must be greater than or equal to "1 GB".'),
error.__str__())
if 'mem_size' in props.keys():
error = self.assertRaises(exception.ValidationError,
props['mem_size'].validate)
self.assertEqual(_('The value "1 MB" of property "mem_size" is '
'out of range "(min:1 MiB, max:1 GiB)".'),
error.__str__())
示例10: _parse_parameters
def _parse_parameters(self, parameter_list):
parsed_inputs = {}
if parameter_list.startswith('--parameters'):
# Parameters are semi-colon separated
inputs = parameter_list.split('--parameters=')[1].\
replace('"', '').split(';')
# Each parameter should be an assignment
for param in inputs:
keyvalue = param.split('=')
# Validate the parameter has both a name and value
msg = _("'%(param)s' is not a well-formed parameter.") % {
'param': param}
if keyvalue.__len__() is 2:
# Assure parameter name is not zero-length or whitespace
stripped_name = keyvalue[0].strip()
if not stripped_name:
log.error(msg)
raise ValueError(msg)
# Add the valid parameter to the dictionary
parsed_inputs[keyvalue[0]] = keyvalue[1]
else:
log.error(msg)
raise ValueError(msg)
else:
msg = _("'%(list)s' is not a valid parameter list.") % {
'list': parameter_list}
log.error(msg)
raise ValueError(msg)
return parsed_inputs
示例11: _validate_and_load_imports
def _validate_and_load_imports(self):
imports_names = set()
if not self.importslist:
msg = _('"imports" keyname is defined without including '
'templates.')
log.error(msg)
ExceptionCollector.appendException(ValidationError(message=msg))
return
for import_def in self.importslist:
if isinstance(import_def, dict):
for import_name, import_uri in import_def.items():
if import_name in imports_names:
msg = (_('Duplicate import name "%s" was found.') %
import_name)
log.error(msg)
ExceptionCollector.appendException(
ValidationError(message=msg))
imports_names.add(import_name)
custom_type = self._load_import_template(import_name,
import_uri)
namespace_prefix = None
if isinstance(import_uri, dict):
namespace_prefix = import_uri.get(
self.NAMESPACE_PREFIX)
self._update_custom_def(custom_type, namespace_prefix)
else: # old style of imports
custom_type = self._load_import_template(None,
import_def)
if custom_type:
self._update_custom_def(custom_type, None)
示例12: convert_unit_size_to_num
def convert_unit_size_to_num(size, unit=None):
"""Convert given size to a number representing given unit.
If unit is None, convert to a number representing UNIT_SIZE_DEFAULT
:param size: unit size e.g. 1 TB
:param unit: unit to be converted to e.g GB
:return: converted number e.g. 1000 for 1 TB size and unit GB
"""
if unit:
unit = MemoryUnit.validate_unit(unit)
else:
unit = MemoryUnit.UNIT_SIZE_DEFAULT
log.info(
_("A memory unit is not provided for size; using the " "default unit %(default)s") % {"default": "B"}
)
regex = re.compile("(\d*)\s*(\w*)")
result = regex.match(str(size)).groups()
if result[1]:
unit_size = MemoryUnit.validate_unit(result[1])
converted = int(
str_to_num(result[0])
* MemoryUnit.UNIT_SIZE_DICT[unit_size]
* math.pow(MemoryUnit.UNIT_SIZE_DICT[unit], -1)
)
log.info(
_("Given size %(size)s is converted to %(num)s " "%(unit)s")
% {"size": size, "num": converted, "unit": unit}
)
else:
converted = str_to_num(result[0])
return converted
示例13: take_action
def take_action(self, parsed_args):
log.debug(_('Translating the template with input parameters'
'(%s).'), parsed_args)
output = None
if parsed_args.parameter:
parsed_params = parsed_args.parameter
else:
parsed_params = {}
if parsed_args.template_type == "tosca":
path = parsed_args.template_file
a_file = os.path.isfile(path)
a_url = UrlUtils.validate_url(path) if not a_file else False
if a_file or a_url:
validate = parsed_args.validate_only
if validate and validate.lower() == "true":
ToscaTemplate(path, parsed_params, a_file)
else:
tosca = ToscaTemplate(path, parsed_params, a_file)
translator = TOSCATranslator(tosca, parsed_params)
output = translator.translate()
else:
msg = _('Could not find template file.')
log.error(msg)
sys.stdout.write(msg)
raise SystemExit
if output:
if parsed_args.output_file:
with open(parsed_args.output_file, 'w+') as f:
f.write(output)
else:
print(output)
示例14: validate
def validate(self):
if len(self.args) < 3:
ExceptionCollector.appendException(
ValueError(
_('Invalid arguments for function "{0}". Expected ' "at least three arguments.").format(TOKEN)
)
)
else:
if not isinstance(self.args[1], str) or len(self.args[1]) != 1:
ExceptionCollector.appendException(
ValueError(
_(
'Invalid arguments for function "{0}". ' "Expected single char value as second " "argument."
).format(TOKEN)
)
)
if not isinstance(self.args[2], int):
ExceptionCollector.appendException(
ValueError(
_(
'Invalid arguments for function "{0}". ' "Expected integer value as third " "argument."
).format(TOKEN)
)
)
示例15: __init__
def __init__(self, name, value=None, schema=None):
self.name = name
self.value = value
self.schema = schema
try:
self.schema['type']
except KeyError:
msg = (_('Schema definition of "%(pname)s" must have a "type" '
'attribute.') % dict(pname=self.name))
ExceptionCollector.appendException(
InvalidSchemaError(message=msg))
if 'required' in self.schema:
required = self.schema['required']
if not isinstance(required, bool):
if required.lower() not in self.VALID_REQUIRED_VALUES:
valid_values = ', '.join(self.VALID_REQUIRED_VALUES)
msg = (_('Schema definition of "%(propname)s" has '
'"required" attribute with invalid value '
'"%(value1)s". The value must be one of '
'"%(value2)s".') % {"propname": self.name,
"value1": required,
"value2": valid_values})
ExceptionCollector.appendException(
InvalidSchemaError(message=msg))