当前位置: 首页>>代码示例>>Python>>正文


Python exceptions.BadRequest方法代码示例

本文整理汇总了Python中novaclient.exceptions.BadRequest方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.BadRequest方法的具体用法?Python exceptions.BadRequest怎么用?Python exceptions.BadRequest使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在novaclient.exceptions的用法示例。


在下文中一共展示了exceptions.BadRequest方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: attach_volume

# 需要导入模块: from novaclient import exceptions [as 别名]
# 或者: from novaclient.exceptions import BadRequest [as 别名]
def attach_volume(context, volume_id, instance_id, device):
    volume = ec2utils.get_db_item(context, volume_id)
    instance = ec2utils.get_db_item(context, instance_id)

    nova = clients.nova(context)
    try:
        nova.volumes.create_server_volume(instance['os_id'], volume['os_id'],
                                          device)
    except (nova_exception.Conflict, nova_exception.BadRequest):
        # TODO(andrey-mp): raise correct errors for different cases
        LOG.exception('Attach has failed.')
        raise exception.UnsupportedOperation()
    cinder = clients.cinder(context)
    os_volume = cinder.volumes.get(volume['os_id'])
    attachment = _format_attachment(context, volume, os_volume,
                                    instance_id=instance_id)
    # NOTE(andrey-mp): nova sets deleteOnTermination=False for attached volume
    attachment['deleteOnTermination'] = False
    return attachment 
开发者ID:openstack,项目名称:ec2-api,代码行数:21,代码来源:volume.py

示例2: translate_server_exception

# 需要导入模块: from novaclient import exceptions [as 别名]
# 或者: from novaclient.exceptions import BadRequest [as 别名]
def translate_server_exception(method):
    """Transforms the exception for the instance.

    Note: keeps its traceback intact.
    """

    @six.wraps(method)
    def wrapper(self, ctx, instance_id, *args, **kwargs):
        try:
            res = method(self, ctx, instance_id, *args, **kwargs)
            return res
        except nova_exception.ClientException as e:
            if isinstance(e, nova_exception.NotFound):
                raise exception.InstanceNotFound(instance_id=instance_id)
            elif isinstance(e, nova_exception.BadRequest):
                raise exception.InvalidInput(reason=six.text_type(e))
            else:
                raise exception.ManilaException(e)

    return wrapper 
开发者ID:openstack,项目名称:manila,代码行数:22,代码来源:nova.py

示例3: delete_volume

# 需要导入模块: from novaclient import exceptions [as 别名]
# 或者: from novaclient.exceptions import BadRequest [as 别名]
def delete_volume(context, volume_id):
    volume = ec2utils.get_db_item(context, volume_id)
    cinder = clients.cinder(context)
    try:
        cinder.volumes.delete(volume['os_id'])
    except cinder_exception.BadRequest:
        # TODO(andrey-mp): raise correct errors for different cases
        raise exception.UnsupportedOperation()
    except cinder_exception.NotFound:
        pass
    # NOTE(andrey-mp) Don't delete item from DB until it disappears from Cloud
    # It will be deleted by describer in the future
    return True 
开发者ID:openstack,项目名称:ec2-api,代码行数:15,代码来源:volume.py

示例4: test_execute_error

# 需要导入模块: from novaclient import exceptions [as 别名]
# 或者: from novaclient.exceptions import BadRequest [as 别名]
def test_execute_error(self):
        @tools.screen_all_logs
        def do_check(ex, status, code, message):
            self.controller.reset_mock()
            self.controller.fake_action.side_effect = ex

            res = self.request.send(self.application)

            self.assertEqual(status, res.status_code)
            self.assertEqual('text/xml', res.content_type)
            expected_xml = fakes.XML_ERROR_TEMPLATE % {
                'code': code,
                'message': message,
                'request_id': self.fake_context.request_id}
            self.assertThat(res.body.decode("utf-8"),
                            matchers.XMLMatches(expected_xml))
            self.controller.fake_action.assert_called_once_with(
                self.fake_context, param='fake_param')

        do_check(exception.EC2Exception('fake_msg'),
                 400, 'EC2Exception', 'fake_msg')
        do_check(KeyError('fake_msg'),
                 500, 'KeyError', 'Unknown error occurred.')
        do_check(exception.InvalidVpcIDNotFound('fake_msg'),
                 400, 'InvalidVpcID.NotFound', 'fake_msg')
        do_check(nova_exception.BadRequest(400, message='fake_msg'),
                 400, 'BadRequest', 'fake_msg')
        do_check(glance_exception.HTTPBadRequest(),
                 400, 'HTTPBadRequest', 'HTTP HTTPBadRequest')
        do_check(cinder_exception.BadRequest(400, message='fake_msg'),
                 400, 'BadRequest', 'fake_msg')
        do_check(neutron_exception.BadRequest(message='fake_msg'),
                 400, 'BadRequest', 'fake_msg')
        do_check(keystone_exception.BadRequest(message='fake_msg'),
                 400, 'BadRequest', 'fake_msg (HTTP 400)')
        do_check(botocore_exceptions.ClientError({'Error':
                                                  {'Code': '', 'Message': ''},
                                                  'Code': 'FakeCode',
                                                  'Message': 'fake_msg'},
                                                 'register_image'),
                 400, 'FakeCode', 'fake_msg') 
开发者ID:openstack,项目名称:ec2-api,代码行数:43,代码来源:test_api_init.py

示例5: _format_exception

# 需要导入模块: from novaclient import exceptions [as 别名]
# 或者: from novaclient.exceptions import BadRequest [as 别名]
def _format_exception(self, exception):
        '''Transform a keystone, nova, neutron  exception into a vimconn exception'''
        if isinstance(exception, (HTTPException, gl1Exceptions.HTTPException, gl1Exceptions.CommunicationError,
                                  ConnectionError, ksExceptions.ConnectionError, neExceptions.ConnectionFailed,
                                  neClient.exceptions.ConnectionFailed)):
            raise vimconn.vimconnConnectionException(type(exception).__name__ + ": " + str(exception))            
        elif isinstance(exception, (nvExceptions.ClientException, ksExceptions.ClientException, 
                                    neExceptions.NeutronException, nvExceptions.BadRequest)):
            raise vimconn.vimconnUnexpectedResponse(type(exception).__name__ + ": " + str(exception))
        elif isinstance(exception, (neExceptions.NetworkNotFoundClient, nvExceptions.NotFound)):
            raise vimconn.vimconnNotFoundException(type(exception).__name__ + ": " + str(exception))
        elif isinstance(exception, nvExceptions.Conflict):
            raise vimconn.vimconnConflictException(type(exception).__name__ + ": " + str(exception))
        else: # ()
            raise vimconn.vimconnConnectionException(type(exception).__name__ + ": " + str(exception)) 
开发者ID:nfvlabs,项目名称:openmano,代码行数:17,代码来源:vimconn_openstack.py

示例6: delete_flavor

# 需要导入模块: from novaclient import exceptions [as 别名]
# 或者: from novaclient.exceptions import BadRequest [as 别名]
def delete_flavor(self,flavor_id):
        '''Deletes a tenant flavor from openstack VIM. Returns the old flavor_id
        '''
        try:
            self._reload_connection()
            self.nova.flavors.delete(flavor_id)
            return flavor_id
        #except nvExceptions.BadRequest as e:
        except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException) as e:
            self._format_exception(e) 
开发者ID:nfvlabs,项目名称:openmano,代码行数:12,代码来源:vimconn_openstack.py

示例7: _generic_paginator

# 需要导入模块: from novaclient import exceptions [as 别名]
# 或者: from novaclient.exceptions import BadRequest [as 别名]
def _generic_paginator(self, f):
        """A generic paginator for OpenStack services

        Takes a callable and recursively runs the "listing" until no more are returned
        by sending the ```marker``` kwarg to offset the search results. We try to rollback
        up to 10 times in the markers in case one was deleted. If we can't rollback after
        10 times, we give up.
        Possible improvement is to roll back in 5s or 10s, but then we have to check for
        uniqueness and do dup removals.
        """
        lists = []
        marker = None
        while True:
            if not lists:
                temp_list = f()
            else:
                for i in range(min(10, len(lists))):
                    list_offset = -(i + 1)
                    marker = lists[list_offset].id
                    try:
                        temp_list = f(marker=marker)
                        break
                    except os_exceptions.BadRequest:
                        continue
                else:
                    raise Exception("Could not get list, maybe mass deletion after 10 marker tries")
            if temp_list:
                lists.extend(temp_list)
            else:
                break
        return lists 
开发者ID:RedHatQE,项目名称:wrapanapi,代码行数:33,代码来源:openstack.py

示例8: test_translate_server_exception_bad_request

# 需要导入模块: from novaclient import exceptions [as 别名]
# 或者: from novaclient.exceptions import BadRequest [as 别名]
def test_translate_server_exception_bad_request(self):
        self.assertRaises(
            exception.InvalidInput,
            decorated_by_translate_server_exception,
            'foo_self', 'foo_ctxt', 'foo_instance_id',
            nova_exception.BadRequest) 
开发者ID:openstack,项目名称:manila,代码行数:8,代码来源:test_nova.py

示例9: translate_nova_exception

# 需要导入模块: from novaclient import exceptions [as 别名]
# 或者: from novaclient.exceptions import BadRequest [as 别名]
def translate_nova_exception(method):
    """Transforms a cinder exception but keeps its traceback intact."""
    @functools.wraps(method)
    def wrapper(self, ctx, *args, **kwargs):
        try:
            res = method(self, ctx, *args, **kwargs)
        except (request_exceptions.Timeout,
                nova_exception.CommandError,
                keystone_exception.ConnectionError) as exc:
            err_msg = encodeutils.exception_to_unicode(exc)
            _reraise(exception.MasakariException(reason=err_msg))
        except (keystone_exception.BadRequest,
                nova_exception.BadRequest) as exc:
            err_msg = encodeutils.exception_to_unicode(exc)
            _reraise(exception.InvalidInput(reason=err_msg))
        except (keystone_exception.Forbidden,
                nova_exception.Forbidden) as exc:
            err_msg = encodeutils.exception_to_unicode(exc)
            _reraise(exception.Forbidden(err_msg))
        except (nova_exception.NotFound) as exc:
            err_msg = encodeutils.exception_to_unicode(exc)
            _reraise(exception.NotFound(reason=err_msg))
        except nova_exception.Conflict as exc:
            err_msg = encodeutils.exception_to_unicode(exc)
            _reraise(exception.Conflict(reason=err_msg))
        return res
    return wrapper 
开发者ID:openstack,项目名称:masakari,代码行数:29,代码来源:nova.py

示例10: test_get_failed_bad_request

# 需要导入模块: from novaclient import exceptions [as 别名]
# 或者: from novaclient.exceptions import BadRequest [as 别名]
def test_get_failed_bad_request(self, mock_novaclient):
        mock_novaclient.return_value.servers.get.side_effect = (
            nova_exception.BadRequest(http.BAD_REQUEST, '400'))

        self.assertRaises(exception.InvalidInput,
                  self.api.get_server, self.ctx, uuidsentinel.fake_server) 
开发者ID:openstack,项目名称:masakari,代码行数:8,代码来源:test_nova.py

示例11: get_vminstance_console

# 需要导入模块: from novaclient import exceptions [as 别名]
# 或者: from novaclient.exceptions import BadRequest [as 别名]
def get_vminstance_console(self,vm_id, console_type="vnc"):
        '''
        Get a console for the virtual machine
        Params:
            vm_id: uuid of the VM
            console_type, can be:
                "novnc" (by default), "xvpvnc" for VNC types, 
                "rdp-html5" for RDP types, "spice-html5" for SPICE types
        Returns dict with the console parameters:
                protocol: ssh, ftp, http, https, ...
                server:   usually ip address 
                port:     the http, ssh, ... port 
                suffix:   extra text, e.g. the http path and query string   
        '''
        self.logger.debug("Getting VM CONSOLE from VIM")
        try:
            self._reload_connection()
            server = self.nova.servers.find(id=vm_id)
            if console_type == None or console_type == "novnc":
                console_dict = server.get_vnc_console("novnc")
            elif console_type == "xvpvnc":
                console_dict = server.get_vnc_console(console_type)
            elif console_type == "rdp-html5":
                console_dict = server.get_rdp_console(console_type)
            elif console_type == "spice-html5":
                console_dict = server.get_spice_console(console_type)
            else:
                raise vimconn.vimconnException("console type '{}' not allowed".format(console_type), http_code=vimconn.HTTP_Bad_Request)
            
            console_dict1 = console_dict.get("console")
            if console_dict1:
                console_url = console_dict1.get("url")
                if console_url:
                    #parse console_url
                    protocol_index = console_url.find("//")
                    suffix_index = console_url[protocol_index+2:].find("/") + protocol_index+2
                    port_index = console_url[protocol_index+2:suffix_index].find(":") + protocol_index+2
                    if protocol_index < 0 or port_index<0 or suffix_index<0:
                        return -vimconn.HTTP_Internal_Server_Error, "Unexpected response from VIM"
                    console_dict={"protocol": console_url[0:protocol_index],
                                  "server":   console_url[protocol_index+2:port_index], 
                                  "port":     console_url[port_index:suffix_index], 
                                  "suffix":   console_url[suffix_index+1:] 
                                  }
                    protocol_index += 2
                    return console_dict
            raise vimconn.vimconnUnexpectedResponse("Unexpected response from VIM")
            
        except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException, nvExceptions.BadRequest) as e:
            self._format_exception(e) 
开发者ID:nfvlabs,项目名称:openmano,代码行数:52,代码来源:vimconn_openstack.py


注:本文中的novaclient.exceptions.BadRequest方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。