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

Python jsonutils.dumps函数代码示例

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

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



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

示例1: _show

    def _show(self, resource_type, response_file,
              uuid1, uuid2=None, relations=None):
        target_uuid = uuid2 or uuid1
        if resource_type.endswith('attachment'):
            resource_type = resource_type[:resource_type.index('attachment')]
        with open("%s/%s" % (self.fake_files_path, response_file)) as f:
            response_template = f.read()
            res_dict = getattr(self, '_fake_%s_dict' % resource_type)
            for item in res_dict.itervalues():
                if 'tags' in item:
                    item['tags_json'] = jsonutils.dumps(item['tags'])

                # replace sec prof rules with their json dump
                def jsonify_rules(rule_key):
                    if rule_key in item:
                        rules_json = jsonutils.dumps(item[rule_key])
                        item['%s_json' % rule_key] = rules_json
                jsonify_rules('logical_port_egress_rules')
                jsonify_rules('logical_port_ingress_rules')

            items = [jsonutils.loads(response_template % res_dict[res_uuid])
                     for res_uuid in res_dict if res_uuid == target_uuid]
            if items:
                return jsonutils.dumps(items[0])
            raise api_exc.ResourceNotFound()
开发者ID:AsherBond,项目名称:quantum,代码行数:25,代码来源:fake.py


示例2: __call__

    def __call__(self, target, creds):
        """
        Check http: rules by calling to a remote server.

        This example implementation simply verifies that the response
        is exactly 'True'.
        """

        url = ('http:' + self.match) % target
        data = {'target': jsonutils.dumps(target),
                'credentials': jsonutils.dumps(creds)}
        post_data = urllib.urlencode(data)
        f = urllib2.urlopen(url, post_data)
        return f.read() == "True"
开发者ID:50infivedays,项目名称:neutron,代码行数:14,代码来源:policy.py


示例3: _lsn_port_configure_action

def _lsn_port_configure_action(
    cluster, lsn_id, lsn_port_id, action, is_enabled, obj):
    nsxlib.do_request(HTTP_PUT,
                      nsxlib._build_uri_path(LSERVICESNODE_RESOURCE,
                                             resource_id=lsn_id,
                                             extra_action=action),
                      json.dumps({"enabled": is_enabled}),
                      cluster=cluster)
    nsxlib.do_request(HTTP_PUT,
                      nsxlib._build_uri_path(LSERVICESNODEPORT_RESOURCE,
                                             parent_resource_id=lsn_id,
                                             resource_id=lsn_port_id,
                                             extra_action=action),
                      json.dumps(obj),
                      cluster=cluster)
开发者ID:brucezy,项目名称:neutron,代码行数:15,代码来源:lsn.py


示例4: _pack_json_msg

    def _pack_json_msg(self, msg):
        """Qpid cannot serialize dicts containing strings longer than 65535
           characters.  This function dumps the message content to a JSON
           string, which Qpid is able to handle.

        :param msg: May be either a Qpid Message object or a bare dict.
        :returns: A Qpid Message with its content field JSON encoded.
        """
        try:
            msg.content = jsonutils.dumps(msg.content)
        except AttributeError:
            # Need to have a Qpid message so we can set the content_type.
            msg = qpid_messaging.Message(jsonutils.dumps(msg))
        msg.content_type = JSON_CONTENT_TYPE
        return msg
开发者ID:50infivedays,项目名称:neutron,代码行数:15,代码来源:impl_qpid.py


示例5: serialize_msg

def serialize_msg(raw_msg):
    # NOTE(russellb) See the docstring for _RPC_ENVELOPE_VERSION for more
    # information about this format.
    msg = {_VERSION_KEY: _RPC_ENVELOPE_VERSION,
           _MESSAGE_KEY: jsonutils.dumps(raw_msg)}

    return msg
开发者ID:50infivedays,项目名称:neutron,代码行数:7,代码来源:common.py


示例6: plug_router_port_attachment

def plug_router_port_attachment(cluster, router_id, port_id,
                                attachment_uuid, nsx_attachment_type,
                                attachment_vlan=None):
    """Attach a router port to the given attachment.

    Current attachment types:
       - PatchAttachment [-> logical switch port uuid]
       - L3GatewayAttachment [-> L3GatewayService uuid]
    For the latter attachment type a VLAN ID can be specified as well.
    """
    uri = _build_uri_path(LROUTERPORT_RESOURCE, port_id, router_id,
                          is_attachment=True)
    attach_obj = {}
    attach_obj["type"] = nsx_attachment_type
    if nsx_attachment_type == "PatchAttachment":
        attach_obj["peer_port_uuid"] = attachment_uuid
    elif nsx_attachment_type == "L3GatewayAttachment":
        attach_obj["l3_gateway_service_uuid"] = attachment_uuid
        if attachment_vlan:
            attach_obj['vlan_id'] = attachment_vlan
    else:
        raise nsx_exc.InvalidAttachmentType(
            attachment_type=nsx_attachment_type)
    return do_request(
        HTTP_PUT, uri, jsonutils.dumps(attach_obj), cluster=cluster)
开发者ID:kavonm,项目名称:neutron,代码行数:25,代码来源:router.py


示例7: create_router_lport

def create_router_lport(cluster, lrouter_uuid, tenant_id, neutron_port_id,
                        display_name, admin_status_enabled, ip_addresses,
                        mac_address=None):
    """Creates a logical port on the assigned logical router."""
    lport_obj = dict(
        admin_status_enabled=admin_status_enabled,
        display_name=display_name,
        tags=utils.get_tags(os_tid=tenant_id, q_port_id=neutron_port_id),
        ip_addresses=ip_addresses,
        type="LogicalRouterPortConfig"
    )
    # Only add the mac_address to lport_obj if present. This is because
    # when creating the fake_ext_gw there is no mac_address present.
    if mac_address:
        lport_obj['mac_address'] = mac_address
    path = _build_uri_path(LROUTERPORT_RESOURCE,
                           parent_resource_id=lrouter_uuid)
    result = do_request(HTTP_POST, path, jsonutils.dumps(lport_obj),
                        cluster=cluster)

    LOG.debug(_("Created logical port %(lport_uuid)s on "
                "logical router %(lrouter_uuid)s"),
              {'lport_uuid': result['uuid'],
               'lrouter_uuid': lrouter_uuid})
    return result
开发者ID:kavonm,项目名称:neutron,代码行数:25,代码来源:router.py


示例8: mk_body

def mk_body(**kwargs):
    """Convenience function creates and dumps dictionary to string.

    :param kwargs: the key/value pirs to be dumped into a json string.
    :returns: a json string.
    """
    return jsonutils.dumps(kwargs, ensure_ascii=False)
开发者ID:AsherBond,项目名称:quantum,代码行数:7,代码来源:__init__.py


示例9: sync_routers

    def sync_routers(self, context, **kwargs):
        """Sync routers according to filters to a specific agent.

        @param context: contain user information
        @param kwargs: host, router_ids
        @return: a list of routers
                 with their interfaces and floating_ips
        """
        router_ids = kwargs.get("router_ids")
        host = kwargs.get("host")
        context = neutron_context.get_admin_context()
        l3plugin = manager.NeutronManager.get_service_plugins()[plugin_constants.L3_ROUTER_NAT]
        if not l3plugin:
            routers = {}
            LOG.error(_("No plugin for L3 routing registered! Will reply " "to l3 agent with empty router dictionary."))
        elif utils.is_extension_supported(l3plugin, constants.L3_AGENT_SCHEDULER_EXT_ALIAS):
            if cfg.CONF.router_auto_schedule:
                l3plugin.auto_schedule_routers(context, host, router_ids)
            routers = l3plugin.list_active_sync_routers_on_active_l3_agent(context, host, router_ids)
        else:
            routers = l3plugin.get_sync_data(context, router_ids)
        plugin = manager.NeutronManager.get_plugin()
        if utils.is_extension_supported(plugin, constants.PORT_BINDING_EXT_ALIAS):
            self._ensure_host_set_on_ports(context, plugin, host, routers)
        LOG.debug(_("Routers returned to l3 agent:\n %s"), jsonutils.dumps(routers, indent=5))
        return routers
开发者ID:kavonm,项目名称:neutron,代码行数:26,代码来源:l3_rpc_base.py


示例10: create_network

    def create_network(self, network):

        tenant_id = network['tenant_id']
        router_external = network['router:external'] is True

        network_obj = {
            "name": network['name'],
            "tenant_id": tenant_id,
            "shared": network['shared'],
            "admin_state_up": network['admin_state_up'],
            "router:external": router_external
        }

        uri = NETWORKS_URI % tenant_id

        response = self.send_request("POST", uri,
                                     body=jsonutils.dumps(network_obj),
                                     resource='network', tenant_id=tenant_id)

        nvsd_net = response.json()

        LOG.debug(_("Network %(id)s created under tenant %(tenant_id)s"),
                  {'id': nvsd_net['id'], 'tenant_id': tenant_id})

        return nvsd_net
开发者ID:Jieming,项目名称:neutron,代码行数:25,代码来源:nvsdlib.py


示例11: _goose_handler

 def _goose_handler(req, res):
     #NOTE: This only handles JSON responses.
     # You can use content type header to test for XML.
     data = jsonutils.loads(res.body)
     data['FOXNSOX:googoose'] = req.GET.get('chewing')
     res.body = jsonutils.dumps(data)
     return res
开发者ID:AsherBond,项目名称:quantum,代码行数:7,代码来源:foxinsocks.py


示例12: sync_routers

    def sync_routers(self, context, **kwargs):
        """Sync routers according to filters to a specific agent.

        @param context: contain user information
        @param kwargs: host, router_ids
        @return: a list of routers
                 with their interfaces and floating_ips
        """
        router_ids = kwargs.get('router_ids')
        host = kwargs.get('host')
        context = neutron_context.get_admin_context()
        plugin = manager.NeutronManager.get_plugin()
        if utils.is_extension_supported(
            plugin, constants.L3_AGENT_SCHEDULER_EXT_ALIAS):
            if cfg.CONF.router_auto_schedule:
                plugin.auto_schedule_routers(context, host, router_ids)
            routers = plugin.list_active_sync_routers_on_active_l3_agent(
                context, host, router_ids)
        else:
            routers = plugin.get_sync_data(context, router_ids)
        if utils.is_extension_supported(
            plugin, constants.PORT_BINDING_EXT_ALIAS):
            self._ensure_host_set_on_ports(context, plugin, host, routers)
        LOG.debug(_("Routers returned to l3 agent:\n %s"),
                  jsonutils.dumps(routers, indent=5))
        return routers
开发者ID:fyafighter,项目名称:neutron,代码行数:26,代码来源:l3_rpc_base.py


示例13: sendjson

 def sendjson(self, method, urlpath, obj=None):
     """Send json to the OpenDaylight controller."""
     headers = {'Content-Type': 'application/json'}
     data = jsonutils.dumps(obj, indent=2) if obj else None
     url = '/'.join([self.url, urlpath])
     LOG.debug("Sending METHOD (%(method)s) URL (%(url)s) JSON (%(obj)s)" %
               {'method': method, 'url': url, 'obj': obj})
     r = requests.request(method, url=url,
                          headers=headers, data=data,
                          auth=self.auth, timeout=self.timeout)
     try:
         r.raise_for_status()
     except Exception as ex:
         LOG.error("Error Sending METHOD (%(method)s) URL (%(url)s)"
                   "JSON (%(obj)s) return: %(r)s ex: %(ex)s rtext: "
                   "%(rtext)s" %
                   {'method': method, 'url': url, 'obj': obj, 'r': r,
                    'ex': ex, 'rtext': r.text})
         import pdb;pdb.set_trace()
         return r
     try:
         return json.loads(r.content)
     except Exception:
         LOG.debug("%s" % r)
         return
开发者ID:nikolas-hermanns,项目名称:gluon-shim-layer-opendaylight,代码行数:25,代码来源:odlc.py


示例14: test_create_port

    def test_create_port(self):
        path = PORTS_URI % (TEST_TENANT, TEST_NET)
        with mock.patch.object(self.nvsdlib, 'send_request') as send_request:
            fixed_ips = [{'ip_address': '10.0.0.2',
                          'subnet_id': TEST_SUBNET}]

            lport = {
                "id": TEST_PORT,
                "name": 'test',
                "device_id": "device_id",
                "device_owner": "device_owner",
                "mac_address": "mac_address",
                "fixed_ips": fixed_ips,
                "admin_state_up": True,
                "network_id": TEST_NET,
                "status": 'ACTIVE'
            }
            self.nvsdlib.create_port(TEST_TENANT, lport)
            expected = {"id": TEST_PORT, "name": 'test',
                        "device_id": "device_id",
                        "device_owner": "device_owner",
                        "mac_address": "mac_address",
                        "ip_address": '10.0.0.2',
                        "subnet_id": TEST_SUBNET,
                        "admin_state_up": True,
                        "network_id": TEST_NET,
                        "status": 'ACTIVE'}
            send_request.assert_called_once_with("POST", path,
                                                 body=json.dumps(expected),
                                                 resource='port',
                                                 tenant_id=TEST_TENANT)
开发者ID:50infivedays,项目名称:neutron,代码行数:31,代码来源:test_nvsdlib.py


示例15: deploy_edge

    def deploy_edge(self, request):
        if (self._unique_router_name and
            not self._validate_edge_name(request['name'])):
            header = {
                'status': 400
            }
            msg = ('Edge name should be unique for tenant. Edge %s '
                   'already exists for default tenant.') % request['name']
            response = {
                'details': msg,
                'errorCode': 10085,
                'rootCauseString': None,
                'moduleName': 'vShield Edge',
                'errorData': None
            }
            return (header, jsonutils.dumps(response))

        self._job_idx = self._job_idx + 1
        job_id = "jobdata-%d" % self._job_idx
        self._edge_idx = self._edge_idx + 1
        edge_id = "edge-%d" % self._edge_idx
        self._jobs[job_id] = edge_id
        self._edges[edge_id] = {
            'name': request['name'],
            'request': request,
            'nat_rules': None,
            'nat_rule_id': 0
        }
        header = {
            'status': 200,
            'location': 'https://host/api/4.0/jobs/%s' % job_id
        }
        response = ''
        return (header, response)
开发者ID:AsherBond,项目名称:quantum,代码行数:34,代码来源:fake_vcns.py


示例16: plug_interface

def plug_interface(cluster, lswitch_id, lport_id, att_obj):
    return nsxlib.do_request(HTTP_PUT,
                             nsxlib._build_uri_path(LSWITCHPORT_RESOURCE,
                                                    lport_id, lswitch_id,
                                                    is_attachment=True),
                             json.dumps(att_obj),
                             cluster=cluster)
开发者ID:PFZheng,项目名称:neutron,代码行数:7,代码来源:switch.py


示例17: create_port

    def create_port(self, tenant_id, port):

        network_id = port["network_id"]
        fixed_ips = port.get("fixed_ips")
        ip_address = None
        subnet_id = None

        if fixed_ips:
            ip_address = fixed_ips[0].get("ip_address")
            subnet_id = fixed_ips[0].get("subnet_id")

        lport = {
            "id": port["id"],
            "name": port["name"],
            "device_id": port["device_id"],
            "device_owner": port["device_owner"],
            "mac_address": port["mac_address"],
            "ip_address": ip_address,
            "subnet_id": subnet_id,
            "admin_state_up": port["admin_state_up"],
            "network_id": network_id,
            "status": port["status"]
        }

        path = PORTS_URI % (tenant_id, network_id)

        self.send_request("POST", path, body=jsonutils.dumps(lport),
                          resource='port', tenant_id=tenant_id)

        LOG.debug(_("Port %(id)s created under tenant %(tenant_id)s"),
                  {'id': port['id'], 'tenant_id': tenant_id})
开发者ID:Jieming,项目名称:neutron,代码行数:31,代码来源:nvsdlib.py


示例18: _bands_handler

 def _bands_handler(req, res):
     #NOTE: This only handles JSON responses.
     # You can use content type header to test for XML.
     data = jsonutils.loads(res.body)
     data['FOXNSOX:big_bands'] = 'Pig Bands!'
     res.body = jsonutils.dumps(data)
     return res
开发者ID:AsherBond,项目名称:quantum,代码行数:7,代码来源:foxinsocks.py


示例19: lease_update

    def lease_update(cls):
        network_id = os.environ.get(cls.NEUTRON_NETWORK_ID_KEY)
        dhcp_relay_socket = os.environ.get(cls.NEUTRON_RELAY_SOCKET_PATH_KEY)

        action = sys.argv[1]
        if action not in ("add", "del", "old"):
            sys.exit()

        mac_address = sys.argv[2]
        ip_address = sys.argv[3]

        if action == "del":
            lease_remaining = 0
        else:
            lease_remaining = int(os.environ.get("DNSMASQ_TIME_REMAINING", 0))

        data = dict(
            network_id=network_id, mac_address=mac_address, ip_address=ip_address, lease_remaining=lease_remaining
        )

        if os.path.exists(dhcp_relay_socket):
            sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            sock.connect(dhcp_relay_socket)
            sock.send(jsonutils.dumps(data))
            sock.close()
开发者ID:home-dog,项目名称:neutron,代码行数:25,代码来源:dhcp.py


示例20: format

    def format(self, record):
        message = {'message': record.getMessage(),
                   'asctime': self.formatTime(record, self.datefmt),
                   'name': record.name,
                   'msg': record.msg,
                   'args': record.args,
                   'levelname': record.levelname,
                   'levelno': record.levelno,
                   'pathname': record.pathname,
                   'filename': record.filename,
                   'module': record.module,
                   'lineno': record.lineno,
                   'funcname': record.funcName,
                   'created': record.created,
                   'msecs': record.msecs,
                   'relative_created': record.relativeCreated,
                   'thread': record.thread,
                   'thread_name': record.threadName,
                   'process_name': record.processName,
                   'process': record.process,
                   'traceback': None}

        if hasattr(record, 'extra'):
            message['extra'] = record.extra

        if record.exc_info:
            message['traceback'] = self.formatException(record.exc_info)

        return jsonutils.dumps(message)
开发者ID:AsherBond,项目名称:quantum,代码行数:29,代码来源:log.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python jsonutils.loads函数代码示例发布时间:2022-05-27
下一篇:
Python importutils.import_object函数代码示例发布时间: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