• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python utils.safe_encode_dict函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中neutronclient.common.utils.safe_encode_dict函数的典型用法代码示例。如果您正苦于以下问题:Python safe_encode_dict函数的具体用法?Python safe_encode_dict怎么用?Python safe_encode_dict使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: test_do_request_unicode

    def test_do_request_unicode(self):
        self.client.format = self.format
        self.mox.StubOutWithMock(self.client.httpclient, "request")
        unicode_text = u'\u7f51\u7edc'
        # url with unicode
        action = u'/test'
        expected_action = action
        # query string with unicode
        params = {'test': unicode_text}
        expect_query = urlparse.urlencode(utils.safe_encode_dict(params))
        # request body with unicode
        body = params
        expect_body = self.client.serialize(body)
        self.client.httpclient.auth_token = encodeutils.safe_encode(
            unicode_text)
        expected_auth_token = encodeutils.safe_encode(unicode_text)

        self.client.httpclient.request(
            end_url(expected_action, query=expect_query, format=self.format),
            'PUT', body=expect_body,
            headers=mox.ContainsKeyValue(
                'X-Auth-Token',
                expected_auth_token)).AndReturn((MyResp(200), expect_body))

        self.mox.ReplayAll()
        res_body = self.client.do_request('PUT', action, body=body,
                                          params=params)
        self.mox.VerifyAll()
        self.mox.UnsetStubs()

        # test response with unicode
        self.assertEqual(res_body, body)
开发者ID:gocloudxyz,项目名称:rackspace-python-neutronclient,代码行数:32,代码来源:test_cli20.py


示例2: _cs_request

    def _cs_request(self, *args, **kwargs):
        kargs = {}
        kargs.setdefault("headers", kwargs.get("headers", {}))
        kargs["headers"]["User-Agent"] = self.USER_AGENT

        if "body" in kwargs:
            kargs["body"] = kwargs["body"]
        args = utils.safe_encode_list(args)
        kargs = utils.safe_encode_dict(kargs)

        if self.log_credentials:
            log_kargs = kargs
        else:
            log_kargs = self._strip_credentials(kargs)

        utils.http_log_req(_logger, args, log_kargs)
        try:
            resp, body = self.request(*args, **kargs)
        except requests.exceptions.SSLError as e:
            raise exceptions.SslCertificateValidationError(reason=e)
        except Exception as e:
            # Wrap the low-level connection error (socket timeout, redirect
            # limit, decompression error, etc) into our custom high-level
            # connection exception (it is excepted in the upper layers of code)
            _logger.debug("throwing ConnectionFailed : %s", e)
            raise exceptions.ConnectionFailed(reason=e)
        utils.http_log_resp(_logger, resp, body)
        if resp.status_code == 401:
            raise exceptions.Unauthorized(message=body)
        return resp, body
开发者ID:yanheven,项目名称:OpenStackInAction,代码行数:30,代码来源:client.py


示例3: _build_test_data

    def _build_test_data(self, data, excess=0):
        # Length of a query filter on security group rule id
        # in these testcases, id='secgroupid%02d' (with len(id)=12)
        sec_group_id_filter_len = 12

        response = []
        replace_rules = {'security_group_id': 'security_group',
                         'remote_group_id': 'remote_group'}

        search_opts = {'fields': ['id', 'name']}
        sec_group_ids = set()
        for rule in data:
            for key in replace_rules:
                sec_group_ids.add(rule[key])
                response.append({'id': rule[key], 'name': 'default'})
        sec_group_ids = list(sec_group_ids)

        result = []

        sec_group_count = len(sec_group_ids)
        max_size = ((sec_group_id_filter_len * sec_group_count) - excess)
        chunk_size = max_size / sec_group_id_filter_len

        for i in range(0, sec_group_count, chunk_size):
            search_opts['id'] = sec_group_ids[i: i + chunk_size]
            params = utils.safe_encode_dict(search_opts)
            resp_str = self.client.serialize({'security_groups': response})

            result.append({
                'filter': six.moves.urllib.parse.urlencode(params, doseq=1),
                'response': (test_cli20.MyResp(200), resp_str),
            })

        return result
开发者ID:AsherBond,项目名称:python-quantumclient,代码行数:34,代码来源:test_cli20_securitygroup.py


示例4: test_do_request_unicode

    def test_do_request_unicode(self):
        self.mox.StubOutWithMock(self.client.httpclient, "request")
        unicode_text = u"\u7f51\u7edc"
        # url with unicode
        action = u"/test"
        expected_action = action
        # query string with unicode
        params = {"test": unicode_text}
        expect_query = urlparse.urlencode(utils.safe_encode_dict(params))
        # request body with unicode
        body = params
        expect_body = self.client.serialize(body)
        self.client.httpclient.auth_token = encodeutils.safe_encode(unicode_text)
        expected_auth_token = encodeutils.safe_encode(unicode_text)
        resp_headers = {"x-openstack-request-id": REQUEST_ID}

        self.client.httpclient.request(
            end_url(expected_action, query=expect_query, format=self.format),
            "PUT",
            body=expect_body,
            headers=mox.ContainsKeyValue("X-Auth-Token", expected_auth_token),
        ).AndReturn((MyResp(200, resp_headers), expect_body))

        self.mox.ReplayAll()
        result = self.client.do_request("PUT", action, body=body, params=params)
        self.mox.VerifyAll()
        self.mox.UnsetStubs()

        # test response with unicode
        self.assertEqual(body, result)
开发者ID:Juniper,项目名称:python-neutronclient,代码行数:30,代码来源:test_cli20.py


示例5: test_do_request_unicode

    def test_do_request_unicode(self):
        unicode_text = u'\u7f51\u7edc'
        # url with unicode
        action = u'/test'
        expected_action = action
        # query string with unicode
        params = {'test': unicode_text}
        expect_query = urlparse.urlencode(utils.safe_encode_dict(params))
        # request body with unicode
        body = params
        expect_body = self.client.serialize(body)
        self.client.httpclient.auth_token = encodeutils.safe_encode(
            unicode_text)
        expected_auth_token = encodeutils.safe_encode(unicode_text)
        resp_headers = {'x-openstack-request-id': REQUEST_ID}
        resp = (MyResp(200, resp_headers), expect_body)

        with mock.patch.object(self.client.httpclient, "request",
                               return_value=resp) as mock_request:
            result = self.client.do_request('PUT', action, body=body,
                                            params=params)

        mock_request.assert_called_once_with(
            end_url(expected_action, query=expect_query),
            'PUT', body=expect_body,
            headers=ContainsKeyValue({'X-Auth-Token': expected_auth_token}))
        # test response with unicode
        self.assertEqual(body, result)
开发者ID:openstack,项目名称:python-neutronclient,代码行数:28,代码来源:test_cli20.py


示例6: _cs_request

    def _cs_request(self, *args, **kwargs):
        kargs = {}
        kargs.setdefault('headers', kwargs.get('headers', {}))
        kargs['headers']['User-Agent'] = self.USER_AGENT

        if 'content_type' in kwargs:
            kargs['headers']['Content-Type'] = kwargs['content_type']
            kargs['headers']['Accept'] = kwargs['content_type']
        else:
            kargs['headers']['Content-Type'] = self.content_type
            kargs['headers']['Accept'] = self.content_type

        if 'body' in kwargs:
            kargs['body'] = kwargs['body']
        args = utils.safe_encode_list(args)
        kargs = utils.safe_encode_dict(kargs)
        utils.http_log_req(_logger, args, kargs)
        try:
            resp, body = self.request(*args, **kargs)
        except Exception as e:
            # Wrap the low-level connection error (socket timeout, redirect
            # limit, decompression error, etc) into our custom high-level
            # connection exception (it is excepted in the upper layers of code)
            raise exceptions.ConnectionFailed(reason=e)
        utils.http_log_resp(_logger, resp, body)
        status_code = self.get_status_code(resp)
        if status_code == 401:
            raise exceptions.Unauthorized(message=body)
        elif status_code == 403:
            raise exceptions.Forbidden(message=body)
        return resp, body
开发者ID:CiscoSystems,项目名称:python-neutronclient,代码行数:31,代码来源:client.py


示例7: _cs_request

    def _cs_request(self, *args, **kwargs):
        kargs = {}
        kargs.setdefault('headers', kwargs.get('headers', {}))
        kargs['headers']['User-Agent'] = self.USER_AGENT

        if 'content_type' in kwargs:
            kargs['headers']['Content-Type'] = kwargs['content_type']
            kargs['headers']['Accept'] = kwargs['content_type']
        else:
            kargs['headers']['Content-Type'] = self.content_type
            kargs['headers']['Accept'] = self.content_type

        if 'body' in kwargs:
            kargs['body'] = kwargs['body']
        args = utils.safe_encode_list(args)
        kargs = utils.safe_encode_dict(kargs)

        if self.log_credentials:
            log_kargs = kargs
        else:
            log_kargs = self._strip_credentials(kargs)

        utils.http_log_req(_logger, args, log_kargs)
        try:
            resp, body = self.request(*args, **kargs)
        except httplib2.SSLHandshakeError as e:
            if not _logger.isEnabledFor(logging.DEBUG):
                utils.http_log_req(_logger, args, log_kargs,
                                   force_logging=True)
            raise exceptions.SslCertificateValidationError(reason=e)
        except Exception as e:
            if not _logger.isEnabledFor(logging.DEBUG):
                utils.http_log_req(_logger, args, log_kargs,
                                   force_logging=True)
            # Wrap the low-level connection error (socket timeout, redirect
            # limit, decompression error, etc) into our custom high-level
            # connection exception (it is excepted in the upper layers of code)
            _logger.debug("throwing ConnectionFailed : %s", e)
            raise exceptions.ConnectionFailed(reason=e)
        finally:
            # Temporary Fix for gate failures. RPC calls and HTTP requests
            # seem to be stepping on each other resulting in bogus fd's being
            # picked up for making http requests
            self.connections.clear()
        utils.http_log_resp(_logger, resp, body)
        status_code = self.get_status_code(resp)
        if status_code == 401:
            raise exceptions.Unauthorized(message=body)
        elif status_code == 403:
            raise exceptions.Forbidden(message=body)
        return resp, body
开发者ID:CingHu,项目名称:neutronclient-ustack,代码行数:51,代码来源:client.py


示例8: _request

    def _request(self, url, method, body=None, headers=None, **kwargs):
        kwargs.setdefault("user_agent", self.USER_AGENT)
        kwargs.setdefault("auth", self.auth)
        kwargs.setdefault("authenticated", False)
        kwargs.setdefault("raise_exc", False)

        endpoint_filter = kwargs.setdefault("endpoint_filter", {})
        endpoint_filter.setdefault("interface", self.interface)
        endpoint_filter.setdefault("service_type", self.service_type)
        endpoint_filter.setdefault("region_name", self.region_name)

        kwargs = utils.safe_encode_dict(kwargs)
        resp = self.session.request(url, method, data=body, headers=headers, **kwargs)
        return resp, resp.text
开发者ID:yanheven,项目名称:OpenStackInAction,代码行数:14,代码来源:client.py


示例9: _request

    def _request(self, url, method, body=None, headers=None, **kwargs):
        kwargs.setdefault('user_agent', self.USER_AGENT)
        kwargs.setdefault('auth', self.auth)
        kwargs.setdefault('authenticated', False)

        endpoint_filter = kwargs.setdefault('endpoint_filter', {})
        endpoint_filter.setdefault('interface', self.interface)
        endpoint_filter.setdefault('service_type', self.service_type)
        endpoint_filter.setdefault('region_name', self.region_name)

        kwargs = utils.safe_encode_dict(kwargs)
        resp = self.session.request(url, method, data=body, headers=headers,
                                    **kwargs)
        return resp, resp.text
开发者ID:cboling,项目名称:SDNdbg,代码行数:14,代码来源:client.py


示例10: request

    def request(self, url, method, **kwargs):
        kwargs.setdefault('user_agent', self.USER_AGENT)
        kwargs.setdefault('auth', self.auth)
        kwargs.setdefault('authenticated', False)

        try:
            kwargs['data'] = kwargs.pop('body')
        except KeyError:
            pass

        endpoint_filter = kwargs.setdefault('endpoint_filter', {})
        endpoint_filter.setdefault('interface', self.interface)
        endpoint_filter.setdefault('service_type', self.service_type)
        endpoint_filter.setdefault('region_name', self.region_name)

        kwargs = utils.safe_encode_dict(kwargs)
        resp = self.session.request(url, method, **kwargs)
        return resp, resp.text
开发者ID:group-policy,项目名称:python-neutronclient,代码行数:18,代码来源:client.py


示例11: test_safe_encode_dict

 def test_safe_encode_dict(self):
     o = object()
     unicode_text = u"\u7f51\u7edc"
     d = {
         "test1": unicode_text,
         "test2": [unicode_text, o],
         "test3": o,
         "test4": {"test5": unicode_text},
         "test6": unicode_text.encode("utf-8"),
     }
     expected = {
         "test1": unicode_text.encode("utf-8"),
         "test2": [unicode_text.encode("utf-8"), o],
         "test3": o,
         "test4": {"test5": unicode_text.encode("utf-8")},
         "test6": unicode_text.encode("utf-8"),
     }
     self.assertEqual(utils.safe_encode_dict(d), expected)
开发者ID:cisco-pnsc,项目名称:python-neutronclient,代码行数:18,代码来源:test_utils.py


示例12: do_request

    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()
        self._check_uri_length(action)

        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)
开发者ID:seanmccully,项目名称:python-neutronclient,代码行数:20,代码来源:client.py


示例13: do_request

    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)

        if body:
            body = self.serialize(body)
        resp, replybody = self.httpclient.do_request(
            action, method, body=body, content_type=self.content_type())
        status_code = resp.status_code
        if status_code in (requests.codes.ok,
                           requests.codes.created,
                           requests.codes.accepted,
                           requests.codes.no_content):
            return self.deserialize(replybody, status_code)
        else:
            if not replybody:
                replybody = resp.reason
            self._handle_fault_response(status_code, replybody)
开发者ID:hninthidawin,项目名称:python-group-based-policy-client,代码行数:22,代码来源:client.py


示例14: _build_test_data

    def _build_test_data(self, data, excess=0):
        # Length of a query filter on security group rule id
        # in these testcases, id='secgroupid%02d' (with len(id)=12)
        sec_group_id_filter_len = 12

        response = []
        replace_rules = {"security_group_id": "security_group", "remote_group_id": "remote_group"}

        search_opts = {"fields": ["id", "name"]}
        sec_group_ids = set()
        for rule in data:
            for key in replace_rules:
                if rule.get(key):
                    sec_group_ids.add(rule[key])
                    response.append({"id": rule[key], "name": "default"})
        sec_group_ids = list(sec_group_ids)

        result = []

        sec_group_count = len(sec_group_ids)
        max_size = (sec_group_id_filter_len * sec_group_count) - excess
        chunk_size = max_size // sec_group_id_filter_len

        for i in range(0, sec_group_count, chunk_size):
            search_opts["id"] = sec_group_ids[i : i + chunk_size]
            params = utils.safe_encode_dict(search_opts)
            resp_str = self.client.serialize({"security_groups": response})

            result.append(
                {
                    "filter": six.moves.urllib.parse.urlencode(params, doseq=1),
                    "response": (test_cli20.MyResp(200), resp_str),
                }
            )

        return result
开发者ID:ChameleonCloud,项目名称:python-neutronclient,代码行数:36,代码来源:test_cli20_securitygroup.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python utils.str2dict函数代码示例发布时间:2022-05-27
下一篇:
Python utils.get_item_properties函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap