本文整理汇总了Python中senlinclient.common.i18n._函数的典型用法代码示例。如果您正苦于以下问题:Python _函数的具体用法?Python _怎么用?Python _使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了_函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_parser
def get_parser(self, prog_name):
parser = super(ClusterPolicyList, self).get_parser(prog_name)
parser.add_argument(
'--filters',
metavar='<key1=value1;key2=value2...>',
help=_("Filter parameters to apply on returned results. "
"This can be specified multiple times, or once with "
"parameters separated by a semicolon. The valid filter "
"keys are: ['type', 'name']"),
action='append'
)
parser.add_argument(
'--sort',
metavar='<sort_string>',
help=_("Sorting option which is a string containing a list of "
"keys separated by commas. Each key can be optionally "
"appended by a sort direction (:asc or :desc). The valid "
"sort keys are: ['type', 'name', 'created_at', "
"'updated_at']")
)
parser.add_argument(
'--full-id',
default=False,
action="store_true",
help=_('Print full IDs in list')
)
parser.add_argument(
'cluster',
metavar='<cluster>',
help=_('Name or ID of cluster to query on')
)
return parser
示例2: do_profile_create
def do_profile_create(service, args):
"""Create a profile."""
spec = utils.get_spec_content(args.spec_file)
type_name = spec.get('type', None)
type_version = spec.get('version', None)
properties = spec.get('properties', None)
if type_name is None:
raise exc.CommandError(_("Missing 'type' key in spec file."))
if type_version is None:
raise exc.CommandError(_("Missing 'version' key in spec file."))
if properties is None:
raise exc.CommandError(_("Missing 'properties' key in spec file."))
if type_name == 'os.heat.stack':
stack_properties = utils.process_stack_spec(properties)
spec['properties'] = stack_properties
params = {
'name': args.name,
'spec': spec,
'metadata': utils.format_parameters(args.metadata),
}
profile = service.create_profile(**params)
_show_profile(service, profile.id)
示例3: take_action
def take_action(self, parsed_args):
self.log.debug("take_action(%s)", parsed_args)
senlin_client = self.app.client_manager.clustering
spec = senlin_utils.get_spec_content(parsed_args.spec_file)
type_name = spec.get('type', None)
type_version = spec.get('version', None)
properties = spec.get('properties', None)
if type_name is None:
raise exc.CommandError(_("Missing 'type' key in spec file."))
if type_version is None:
raise exc.CommandError(_("Missing 'version' key in spec file."))
if properties is None:
raise exc.CommandError(_("Missing 'properties' key in spec file."))
if type_name == 'os.heat.stack':
stack_properties = senlin_utils.process_stack_spec(properties)
spec['properties'] = stack_properties
params = {
'name': parsed_args.name,
'spec': spec,
'metadata': senlin_utils.format_parameters(parsed_args.metadata),
}
profile = senlin_client.create_profile(**params)
return _show_profile(senlin_client, profile_id=profile.id)
示例4: get_parser
def get_parser(self, prog_name):
parser = super(UpdateNode, self).get_parser(prog_name)
parser.add_argument(
'--name',
metavar='<name>',
help=_('New name for the node')
)
parser.add_argument(
'--profile',
metavar='<profile_id>',
help=_('ID of new profile to use')
)
parser.add_argument(
'--role',
metavar='<role>',
help=_('Role for this node in the specific cluster')
)
parser.add_argument(
'--metadata',
metavar='<key1=value1;key2=value2...>',
help=_('Metadata values to be attached to the node. '
'Metadata can be specified multiple times, or once with '
'key-value pairs separated by a semicolon'),
action='append'
)
parser.add_argument(
'node',
metavar='<node>',
help=_('Name or ID of node to update')
)
return parser
示例5: process_stack_spec
def process_stack_spec(spec):
# Heat stack is a headache, because it demands for client side file
# content processing
try:
tmplfile = spec.get('template', None)
except AttributeError as ex:
raise exc.FileFormatError(_('The specified file is not a valid '
'YAML file: %s') % six.text_type(ex))
if not tmplfile:
raise exc.FileFormatError(_('No template found in the given '
'spec file'))
tpl_files, template = template_utils.get_template_contents(
template_file=tmplfile)
env_files, env = template_utils.process_multiple_environments_and_files(
env_paths=spec.get('environment', None))
new_spec = {
# TODO(Qiming): add context support
'disable_rollback': spec.get('disable_rollback', True),
'context': spec.get('context', {}),
'parameters': spec.get('parameters', {}),
'timeout': spec.get('timeout', 60),
'template': template,
'files': dict(list(tpl_files.items()) + list(env_files.items())),
'environment': env
}
return new_spec
示例6: get_parser
def get_parser(self, prog_name):
parser = super(UpdateCluster, self).get_parser(prog_name)
parser.add_argument(
'--profile',
metavar='<profile>',
help=_('ID or name of new profile to use')
)
parser.add_argument(
'--timeout',
metavar='<timeout>',
help=_('New timeout (in seconds) value for the cluster')
)
parser.add_argument(
'--metadata',
metavar='<key1=value1;key2=value2...>',
help=_('Metadata values to be attached to the cluster. '
'This can be specified multiple times, or once with '
'key-value pairs separated by a semicolon'),
action='append'
)
parser.add_argument(
'--name',
metavar='<name>',
help=_('New name for the cluster to update')
)
parser.add_argument(
'cluster',
metavar='<cluster>',
help=_('Name or ID of cluster to be updated')
)
return parser
示例7: take_action
def take_action(self, parsed_args):
self.log.debug("take_action(%s)", parsed_args)
senlin_client = self.app.client_manager.clustering
try:
if not parsed_args.force and sys.stdin.isatty():
sys.stdout.write(
_("Are you sure you want to delete this node(s)"
" [y/N]?"))
prompt_response = sys.stdin.readline().lower()
if not prompt_response.startswith('y'):
return
except KeyboardInterrupt: # Ctrl-c
self.log.info(_LI('Ctrl-c detected.'))
return
except EOFError: # Ctrl-d
self.log.info(_LI('Ctrl-d detected'))
return
failure_count = 0
for nid in parsed_args.node:
try:
senlin_client.delete_node(nid, False)
except Exception as ex:
failure_count += 1
print(ex)
if failure_count:
raise exc.CommandError(_('Failed to delete %(count)s of the '
'%(total)s specified node(s).') %
{'count': failure_count,
'total': len(parsed_args.node)})
print('Request accepted')
示例8: add_global_args
def add_global_args(parser, version):
# GLOBAL ARGUMENTS
parser.add_argument(
'-h', '--help', action='store_true',
help=argparse.SUPPRESS)
parser.add_argument(
'--version', action='version', version=version,
help=_("Shows the client version and exits."))
parser.add_argument(
'-d', '--debug', action='store_true',
default=bool(utils.env('SENLINCLIENT_DEBUG')),
help=_('Defaults to env[SENLINCLIENT_DEBUG].'))
parser.add_argument(
'-v', '--verbose', action="store_true", default=False,
help=_("Print more verbose output."))
parser.add_argument(
'--api-timeout',
help=_('Number of seconds to wait for an API response, '
'defaults to system socket timeout'))
parser.add_argument(
'--senlin-api-version',
default=utils.env('SENLIN_API_VERSION', default='1'),
help=_('Version number for Senlin API to use, Default to "1".'))
示例9: get_parser
def get_parser(self, prog_name):
parser = super(CreateReceiver, self).get_parser(prog_name)
parser.add_argument(
'--type',
metavar='<type>',
default='webhook',
help=_('Type of the receiver to create')
)
parser.add_argument(
'--cluster',
metavar='<cluster>',
required=True,
help=_('Targeted cluster for this receiver')
)
parser.add_argument(
'--action',
metavar='<action>',
required=True,
help=_('Name or ID of the targeted action to be triggered')
)
parser.add_argument(
'--params',
metavar='<key1=value1;key2=value2...>',
help=_('A dictionary of parameters that will be passed to target '
'action when the receiver is triggered'),
action='append'
)
parser.add_argument(
'name',
metavar='<name>',
help=_('Name of the receiver to create')
)
return parser
示例10: parse_exception
def parse_exception(exc):
"""Parse exception code and yield useful information.
:param details: details of the exception.
"""
if isinstance(exc, sdkexc.HttpException):
try:
record = jsonutils.loads(exc.details)
except Exception:
# If the exc.details is not in JSON format
record = {
'error': {
'code': exc.http_status,
'message': exc.details,
}
}
elif isinstance(exc, reqexc.RequestException):
# Exceptions that are not captured by SDK
record = {
'error': {
'code': exc.message[1].errno,
'message': exc.message[0],
}
}
elif isinstance(exc, six.string_types):
record = jsonutils.loads(exc)
# some exception from keystoneauth1 is not shaped by SDK
elif isinstance(exc, kae_http.HttpError):
record = {
'error': {
'code': exc.http_status,
'message': exc.message
}
}
elif isinstance(exc, kae_base.ClientException):
record = {
'error': {
# other exceptions from keystoneauth1 is an internal
# error to senlin, so set status code to 500
'code': 500,
'message': exc.message
}
}
else:
print(_('Unknown exception: %s') % exc)
return
try:
code = record['error']['code']
except KeyError as err:
print(_('Malformed exception record, missing field "%s"') % err)
print(_('Original error record: %s') % record)
return
if code in _EXCEPTION_MAP:
inst = _EXCEPTION_MAP.get(code)
raise inst(record)
else:
raise HTTPException(record)
示例11: __str__
def __str__(self):
message = self.error['error'].get('message', 'Internal Error')
if verbose:
traceback = self.error['error'].get('traceback', '')
return (_('ERROR: %(message)s\n%(traceback)s') %
{'message': message, 'traceback': traceback})
else:
code = self.error['error'].get('code', 'Unknown')
return _('ERROR(%(code)s): %(message)s') % {'code': code,
'message': message}
示例12: get_parser
def get_parser(self, prog_name):
parser = super(UpdatePolicy, self).get_parser(prog_name)
parser.add_argument(
'--name',
metavar='<name>',
help=_('New name of the policy to be updated')
)
parser.add_argument(
'policy',
metavar='<policy>',
help=_('Name or ID of the policy to be updated')
)
return parser
示例13: test_do_profile_create
def test_do_profile_create(self, mock_get, mock_proc, mock_format,
mock_show):
args = copy.deepcopy(self.profile_args)
args = self._make_args(args)
spec = copy.deepcopy(self.profile_spec)
mock_get.return_value = spec
stack_properties = mock.Mock()
mock_proc.return_value = stack_properties
mock_format.return_value = {'user': 'demo'}
params = {
'name': 'stack_spec',
'spec': spec,
'metadata': {'user': 'demo'},
}
service = mock.Mock()
profile = mock.Mock()
profile_id = mock.Mock()
profile.id = profile_id
service.create_profile.return_value = profile
sh.do_profile_create(service, args)
mock_get.assert_called_once_with(args.spec_file)
mock_proc.assert_called_once_with(self.profile_spec['properties'])
mock_format.assert_called_once_with(args.metadata)
service.create_profile.assert_called_once_with(**params)
mock_show.assert_called_once_with(service, profile_id)
# Miss 'type' key in spec file
del spec['type']
ex = self.assertRaises(exc.CommandError,
sh.do_profile_create,
service, args)
self.assertEqual(_("Missing 'type' key in spec file."),
six.text_type(ex))
# Miss 'version' key in spec file
spec['type'] = 'os.heat.stack'
del spec['version']
ex = self.assertRaises(exc.CommandError,
sh.do_profile_create,
service, args)
self.assertEqual(_("Missing 'version' key in spec file."),
six.text_type(ex))
# Miss 'properties' key in spec file
spec['version'] = 1.0
del spec['properties']
ex = self.assertRaises(exc.CommandError,
sh.do_profile_create,
service, args)
self.assertEqual(_("Missing 'properties' key in spec file."),
six.text_type(ex))
示例14: format_parameters
def format_parameters(params, parse_semicolon=True):
"""Reformat parameters into dict of format expected by the API."""
if not params:
return {}
if parse_semicolon:
# expect multiple invocations of --parameters but fall back to ';'
# delimited if only one --parameters is specified
if len(params) == 1:
params = params[0].split(';')
parameters = {}
for p in params:
try:
(n, v) = p.split(('='), 1)
except ValueError:
msg = _('Malformed parameter(%s). Use the key=value format.') % p
raise exc.CommandError(msg)
if n not in parameters:
parameters[n] = v
else:
if not isinstance(parameters[n], list):
parameters[n] = [parameters[n]]
parameters[n].append(v)
return parameters
示例15: test_do_cluster_node_list
def test_do_cluster_node_list(self, mock_print):
service = mock.Mock()
args = {
'id': 'cluster_id',
'limit': 20,
'marker': 'marker_id',
'filters': ['status=ACTIVE'],
}
queries = copy.deepcopy(args)
queries['cluster_id'] = args['id']
del queries['id']
del queries['filters']
queries['status'] = 'ACTIVE'
args = self._make_args(args)
args.full_id = True
nodes = mock.Mock()
service.nodes.return_value = nodes
formatters = {}
fields = ['id', 'name', 'index', 'status', 'physical_id', 'created_at']
sh.do_cluster_node_list(service, args)
service.nodes.assert_called_once_with(**queries)
mock_print.assert_called_once_with(nodes, fields,
formatters=formatters,
sortby_index=5)
# node not found
service.nodes.side_effect = exc.HTTPNotFound
ex = self.assertRaises(exc.CommandError,
sh.do_cluster_node_list, service, args)
msg = _('No node matching criteria is found')
self.assertEqual(msg, six.text_type(ex))