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


Python HTTPClient.do_request方法代码示例

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


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

示例1: Client

# 需要导入模块: from quantumclient.client import HTTPClient [as 别名]
# 或者: from quantumclient.client.HTTPClient import do_request [as 别名]

#.........这里部分代码省略.........

    @APIParamsCall
    def disassociate_health_monitor(self, pool, health_monitor):
        """
        Disassociate specified load balancer health monitor and pool
        """
        path = (self.disassociate_pool_health_monitors_path %
                {'pool': pool, 'health_monitor': health_monitor})
        return self.delete(path)

    def __init__(self, **kwargs):
        """ Initialize a new client for the Quantum v2.0 API. """
        super(Client, self).__init__()
        self.httpclient = HTTPClient(**kwargs)
        self.version = '2.0'
        self.format = 'json'
        self.action_prefix = "/v%s" % (self.version)
        self.retries = 0
        self.retry_interval = 1

    def _handle_fault_response(self, status_code, response_body):
        # Create exception with HTTP status code and message
        _logger.debug("Error message: %s", response_body)
        # Add deserialized error message to exception arguments
        try:
            des_error_body = self.deserialize(response_body, status_code)
        except:
            # If unable to deserialized body it is probably not a
            # Quantum error
            des_error_body = {'message': response_body}
        # Raise the appropriate exception
        exception_handler_v20(status_code, des_error_body)

    def do_request(self, method, action, body=None, headers=None, params=None):
        # Add format and tenant_id
        action += ".%s" % self.format
        action = self.action_prefix + action
        if type(params) is dict and params:
            action += '?' + urllib.urlencode(params, doseq=1)
        if body:
            body = self.serialize(body)
        self.httpclient.content_type = self.content_type()
        resp, replybody = self.httpclient.do_request(action, method, body=body)
        status_code = self.get_status_code(resp)
        if status_code in (httplib.OK,
                           httplib.CREATED,
                           httplib.ACCEPTED,
                           httplib.NO_CONTENT):
            return self.deserialize(replybody, status_code)
        else:
            self._handle_fault_response(status_code, replybody)

    def get_status_code(self, response):
        """
        Returns the integer status code from the response, which
        can be either a Webob.Response (used in testing) or httplib.Response
        """
        if hasattr(response, 'status_int'):
            return response.status_int
        else:
            return response.status

    def serialize(self, data):
        """
        Serializes a dictionary with a single key (which can contain any
        structure) into either xml or json
开发者ID:dani4571,项目名称:python-quantumclient,代码行数:70,代码来源:client.py

示例2: Client

# 需要导入模块: from quantumclient.client import HTTPClient [as 别名]
# 或者: from quantumclient.client.HTTPClient import do_request [as 别名]

#.........这里部分代码省略.........

    @APIParamsCall
    def delete_subnet(self, subnet):
        """
        Deletes the specified subnet
        """
        return self.delete(self.subnet_path % (subnet))

    def __init__(self, **kwargs):
        """ Initialize a new client for the Quantum v2.0 API. """
        super(Client, self).__init__()
        self.httpclient = HTTPClient(**kwargs)
        self.version = '2.0'
        self.format = 'json'
        self.action_prefix = "/v%s" % (self.version)
        self.retries = 0
        self.retry_interval = 1

    def _handle_fault_response(self, status_code, response_body):
        # Create exception with HTTP status code and message
        error_message = response_body
        _logger.debug("Error message: %s", error_message)
        # Add deserialized error message to exception arguments
        try:
            des_error_body = Serializer().deserialize(error_message,
                                                      self.content_type())
        except:
            # If unable to deserialized body it is probably not a
            # Quantum error
            des_error_body = {'message': error_message}
        # Raise the appropriate exception
        exception_handler_v20(status_code, des_error_body)

    def do_request(self, method, action, body=None, headers=None, params=None):
        # Add format and tenant_id
        action += ".%s" % self.format
        action = self.action_prefix + action
        if type(params) is dict:
            action += '?' + urllib.urlencode(params, doseq=1)
        if body:
            body = self.serialize(body)
        self.httpclient.content_type = self.content_type()
        resp, replybody = self.httpclient.do_request(action, method, body=body)
        status_code = self.get_status_code(resp)
        if status_code in (httplib.OK,
                           httplib.CREATED,
                           httplib.ACCEPTED,
                           httplib.NO_CONTENT):
            return self.deserialize(replybody, status_code)
        else:
            self._handle_fault_response(status_code, replybody)

    def get_status_code(self, response):
        """
        Returns the integer status code from the response, which
        can be either a Webob.Response (used in testing) or httplib.Response
        """
        if hasattr(response, 'status_int'):
            return response.status_int
        else:
            return response.status

    def serialize(self, data):
        """
        Serializes a dictionary with a single key (which can contain any
        structure) into either xml or json
开发者ID:codeoedoc,项目名称:python-quantumclient,代码行数:70,代码来源:client.py

示例3: CLITestAuthKeystone

# 需要导入模块: from quantumclient.client import HTTPClient [as 别名]
# 或者: from quantumclient.client.HTTPClient import do_request [as 别名]
class CLITestAuthKeystone(unittest.TestCase):

    def setUp(self):
        """Prepare the test environment"""
        self.mox = mox.Mox()
        self.client = HTTPClient(username=USERNAME, tenant_name=TENANT_NAME,
                                 password=PASSWORD, auth_url=AUTH_URL,
                                 region_name=REGION)

    def tearDown(self):
        """Clear the test environment"""
        self.mox.VerifyAll()
        self.mox.UnsetStubs()

    def test_get_token(self):
        self.mox.StubOutWithMock(self.client, "request")

        res200 = self.mox.CreateMock(httplib2.Response)
        res200.status = 200

        self.client.request(AUTH_URL + '/tokens', 'POST',
                            body=IsA(str), headers=IsA(dict)).\
            AndReturn((res200, json.dumps(KS_TOKEN_RESULT)))
        self.client.request(StrContains(ENDPOINT_URL + '/resource'), 'GET',
                            headers=ContainsKeyValue('X-Auth-Token', TOKEN)).\
            AndReturn((res200, ''))
        self.mox.ReplayAll()

        self.client.do_request('/resource', 'GET')
        self.assertEqual(self.client.endpoint_url, ENDPOINT_URL)
        self.assertEqual(self.client.auth_token, TOKEN)
        self.assertEqual(self.client.token_retrieved, True)

    def test_already_token_retrieved(self):
        self.mox.StubOutWithMock(self.client, "request")

        self.client.auth_token = TOKEN
        self.client.endpoint_url = ENDPOINT_URL
        self.client.token_retrieved = True

        res200 = self.mox.CreateMock(httplib2.Response)
        res200.status = 200

        self.client.request(StrContains(ENDPOINT_URL + '/resource'), 'GET',
                            headers=ContainsKeyValue('X-Auth-Token', TOKEN)).\
            AndReturn((res200, ''))
        self.mox.ReplayAll()

        self.client.do_request('/resource', 'GET')

    def test_refresh_token(self):
        self.mox.StubOutWithMock(self.client, "request")

        self.client.auth_token = TOKEN
        self.client.endpoint_url = ENDPOINT_URL
        self.client.token_retrieved = True

        res200 = self.mox.CreateMock(httplib2.Response)
        res200.status = 200
        res401 = self.mox.CreateMock(httplib2.Response)
        res401.status = 401

        # If a token is expired, quantum server retruns 401
        self.client.request(StrContains(ENDPOINT_URL + '/resource'), 'GET',
                            headers=ContainsKeyValue('X-Auth-Token', TOKEN)).\
            AndReturn((res401, ''))
        self.client.request(AUTH_URL + '/tokens', 'POST',
                            body=IsA(str), headers=IsA(dict)).\
            AndReturn((res200, json.dumps(KS_TOKEN_RESULT)))
        self.client.request(StrContains(ENDPOINT_URL + '/resource'), 'GET',
                            headers=ContainsKeyValue('X-Auth-Token', TOKEN)).\
            AndReturn((res200, ''))
        self.mox.ReplayAll()
        self.client.do_request('/resource', 'GET')
开发者ID:akushwah,项目名称:python-quantumclient-n1kv,代码行数:76,代码来源:test_auth.py

示例4: Client

# 需要导入模块: from quantumclient.client import HTTPClient [as 别名]
# 或者: from quantumclient.client.HTTPClient import do_request [as 别名]

#.........这里部分代码省略.........
        return self.delete(self.firewall_path % (firewall))

    @APIParamsCall
    def remove_router_from_l3_agent(self, l3_agent, router_id):
        """
        Remove a router from l3 agent.
        """
        return self.delete((self.agent_path + self.L3_ROUTERS + "/%s") % (
            l3_agent, router_id))

    def __init__(self, **kwargs):
        """Initialize a new client for the Quantum v2.0 API."""
        super(Client, self).__init__()
        self.httpclient = HTTPClient(**kwargs)
        self.version = '2.0'
        self.format = 'json'
        self.action_prefix = "/v%s" % (self.version)
        self.retries = 0
        self.retry_interval = 1

    def _handle_fault_response(self, status_code, response_body):
        # Create exception with HTTP status code and message
        _logger.debug("Error message: %s", response_body)
        # Add deserialized error message to exception arguments
        try:
            des_error_body = self.deserialize(response_body, status_code)
        except Exception:
            # If unable to deserialized body it is probably not a
            # Quantum error
            des_error_body = {'message': response_body}
        # Raise the appropriate exception
        exception_handler_v20(status_code, des_error_body)

    def do_request(self, method, action, body=None, headers=None, params=None):
        # Add format and tenant_id
        action += ".%s" % self.format
        action = self.action_prefix + action
        if type(params) is dict and params:
            params = utils.safe_encode_dict(params)
            action += '?' + urllib.urlencode(params, doseq=1)
        # Ensure client always has correct uri - do not guesstimate anything
        self.httpclient.authenticate_and_fetch_endpoint_url()
        uri_len = len(self.httpclient.endpoint_url) + len(action)
        if uri_len > self.MAX_URI_LEN:
            raise exceptions.RequestURITooLong(
                excess=uri_len - self.MAX_URI_LEN)
        if body:
            body = self.serialize(body)
        self.httpclient.content_type = self.content_type()
        resp, replybody = self.httpclient.do_request(action, method, body=body)
        status_code = self.get_status_code(resp)
        if status_code in (httplib.OK,
                           httplib.CREATED,
                           httplib.ACCEPTED,
                           httplib.NO_CONTENT):
            return self.deserialize(replybody, status_code)
        else:
            self._handle_fault_response(status_code, replybody)

    def get_auth_info(self):
        return self.httpclient.get_auth_info()

    def get_status_code(self, response):
        """
        Returns the integer status code from the response, which
        can be either a Webob.Response (used in testing) or httplib.Response
开发者ID:,项目名称:,代码行数:70,代码来源:

示例5: CLITestAuthKeystone

# 需要导入模块: from quantumclient.client import HTTPClient [as 别名]
# 或者: from quantumclient.client.HTTPClient import do_request [as 别名]
class CLITestAuthKeystone(testtools.TestCase):

    def setUp(self):
        """Prepare the test environment."""
        super(CLITestAuthKeystone, self).setUp()
        self.mox = mox.Mox()
        self.client = HTTPClient(username=USERNAME, tenant_name=TENANT_NAME,
                                 password=PASSWORD, auth_url=AUTH_URL,
                                 region_name=REGION)
        self.addCleanup(self.mox.VerifyAll)
        self.addCleanup(self.mox.UnsetStubs)

    def test_get_token(self):
        self.mox.StubOutWithMock(self.client, "request")

        res200 = self.mox.CreateMock(httplib2.Response)
        res200.status = 200

        self.client.request(AUTH_URL + '/tokens', 'POST',
                            body=IsA(str), headers=IsA(dict)).\
            AndReturn((res200, json.dumps(KS_TOKEN_RESULT)))
        self.client.request(StrContains(ENDPOINT_URL + '/resource'), 'GET',
                            headers=ContainsKeyValue('X-Auth-Token', TOKEN)).\
            AndReturn((res200, ''))
        self.mox.ReplayAll()

        self.client.do_request('/resource', 'GET')
        self.assertEqual(self.client.endpoint_url, ENDPOINT_URL)
        self.assertEqual(self.client.auth_token, TOKEN)

    def test_refresh_token(self):
        self.mox.StubOutWithMock(self.client, "request")

        self.client.auth_token = TOKEN
        self.client.endpoint_url = ENDPOINT_URL

        res200 = self.mox.CreateMock(httplib2.Response)
        res200.status = 200
        res401 = self.mox.CreateMock(httplib2.Response)
        res401.status = 401

        # If a token is expired, quantum server retruns 401
        self.client.request(StrContains(ENDPOINT_URL + '/resource'), 'GET',
                            headers=ContainsKeyValue('X-Auth-Token', TOKEN)).\
            AndReturn((res401, ''))
        self.client.request(AUTH_URL + '/tokens', 'POST',
                            body=IsA(str), headers=IsA(dict)).\
            AndReturn((res200, json.dumps(KS_TOKEN_RESULT)))
        self.client.request(StrContains(ENDPOINT_URL + '/resource'), 'GET',
                            headers=ContainsKeyValue('X-Auth-Token', TOKEN)).\
            AndReturn((res200, ''))
        self.mox.ReplayAll()
        self.client.do_request('/resource', 'GET')

    def test_get_endpoint_url(self):
        self.mox.StubOutWithMock(self.client, "request")

        self.client.auth_token = TOKEN

        res200 = self.mox.CreateMock(httplib2.Response)
        res200.status = 200

        self.client.request(StrContains(AUTH_URL +
                                        '/tokens/%s/endpoints' % TOKEN), 'GET',
                            headers=IsA(dict)). \
            AndReturn((res200, json.dumps(ENDPOINTS_RESULT)))
        self.client.request(StrContains(ENDPOINT_URL + '/resource'), 'GET',
                            headers=ContainsKeyValue('X-Auth-Token', TOKEN)). \
            AndReturn((res200, ''))
        self.mox.ReplayAll()
        self.client.do_request('/resource', 'GET')

    def test_get_endpoint_url_other(self):
        self.client = HTTPClient(username=USERNAME, tenant_name=TENANT_NAME,
                                 password=PASSWORD, auth_url=AUTH_URL,
                                 region_name=REGION, endpoint_type='otherURL')
        self.mox.StubOutWithMock(self.client, "request")

        self.client.auth_token = TOKEN

        res200 = self.mox.CreateMock(httplib2.Response)
        res200.status = 200

        self.client.request(StrContains(AUTH_URL +
                                        '/tokens/%s/endpoints' % TOKEN), 'GET',
                            headers=IsA(dict)). \
            AndReturn((res200, json.dumps(ENDPOINTS_RESULT)))
        self.mox.ReplayAll()
        self.assertRaises(exceptions.EndpointTypeNotFound,
                          self.client.do_request,
                          '/resource',
                          'GET')

    def test_get_endpoint_url_failed(self):
        self.mox.StubOutWithMock(self.client, "request")

        self.client.auth_token = TOKEN

        res200 = self.mox.CreateMock(httplib2.Response)
        res200.status = 200
#.........这里部分代码省略.........
开发者ID:,项目名称:,代码行数:103,代码来源:

示例6: Client

# 需要导入模块: from quantumclient.client import HTTPClient [as 别名]
# 或者: from quantumclient.client.HTTPClient import do_request [as 别名]

#.........这里部分代码省略.........
        
    @APIParamsCall
    def launch_chain(self, launch, **_params):
        """
        Generate the specified configuration
        """       
        return self.get(self.launch_path % (launch), params=_params)

    def __init__(self, **kwargs):
        """ Initialize a new client for the Quantum v2.0 API. """
        super(Client, self).__init__()
        self.httpclient = HTTPClient(**kwargs)
        self.version = '2.0'
        self.format = 'json'
        self.action_prefix = "/v%s" % (self.version)
        self.retries = 0
        self.retry_interval = 1

    def _handle_fault_response(self, status_code, response_body):
        # Create exception with HTTP status code and message
        error_message = response_body
        _logger.debug("Error message: %s", error_message)
        # Add deserialized error message to exception arguments
        try:
            des_error_body = Serializer().deserialize(error_message,
                                                      self.content_type())
        except:
            # If unable to deserialized body it is probably not a
            # Quantum error
            des_error_body = {'message': error_message}
        # Raise the appropriate exception
        exception_handler_v20(status_code, des_error_body)

    def do_request(self, method, action, body=None, headers=None, params=None):
        # Add format and tenant_id
        action += ".%s" % self.format
        action = self.action_prefix + action
        if type(params) is dict and params:
            action += '?' + urllib.urlencode(params, doseq=1)
        if body:
            body = self.serialize(body)
        self.httpclient.content_type = self.content_type()
        resp, replybody = self.httpclient.do_request(action, method, body=body)
        status_code = self.get_status_code(resp)
        if status_code in (httplib.OK,
                           httplib.CREATED,
                           httplib.ACCEPTED,
                           httplib.NO_CONTENT):
            return self.deserialize(replybody, status_code)
        else:
            self._handle_fault_response(status_code, replybody)

    def get_status_code(self, response):
        """
        Returns the integer status code from the response, which
        can be either a Webob.Response (used in testing) or httplib.Response
        """
        if hasattr(response, 'status_int'):
            return response.status_int
        else:
            return response.status

    def serialize(self, data):
        """
        Serializes a dictionary with a single key (which can contain any
        structure) into either xml or json
开发者ID:kumarcv,项目名称:openstack-nf,代码行数:70,代码来源:client.py


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