Python源码示例:xmltodict.unparse()

示例1
def send_cert_request(url, param):
    # dict 2 xml
    param = {'root': param}
    xml = xmltodict.unparse(param)
    '''
    登录微信商户平台(pay.weixin.qq.com)-->账户设置-->API安全-->证书下载
    下载apiclient_cert.p12
    python无法使用双向证书,使用openssl导出:
        openssl pkcs12 -clcerts -nokeys -in apiclient_cert.p12 -out apiclient_cert.pem
        openssl pkcs12 -nocerts -in apiclient_cert.p12 -out apiclient_key.pem
    导出apiclient_key.pem时需输入PEM phrase, 此后每次发起请求均要输入,可使用openssl解除:
        openssl rsa -in apiclient_key.pem -out apiclient_key.pem.unsecure
    '''
    response = requests.post(url, data=xml.encode('utf-8'),
                             headers={'Content-Type': 'text/xml'},
                             cert=(WX_CERT_PATH, WX_KEY_PATH))
    # xml 2 dict
    msg = response.text
    xmlmsg = xmltodict.parse(msg)

    return xmlmsg 
示例2
def prepare_request(self, method, path, params):
        kwargs = {}
        _params = self.get_base_params()
        params.update(_params)
        newparams, prestr = params_filter(params)
        sign = build_mysign(prestr, self.partner_key)
        # 将内容转化为unicode xmltodict 只支持unicode
        newparams = params_encoding(newparams)
        newparams['sign'] = sign
        xml_dict = {'xml': newparams}
        kwargs['data'] = smart_str(xmltodict.unparse(xml_dict))
        url = self._full_url(path)
        if self.mch_cert and self.mch_key:
            kwargs['cert'] = (self.mch_cert, self.mch_key)
        return method, url, kwargs

    # 统一下单
    # https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1 
示例3
def prepare_request(self, method, path, params):
        kwargs = {}
        _params = self.get_base_params()
        params.update(_params)
        newparams, prestr = params_filter(params)
        sign = build_mysign(prestr, key=self.partner_key)
        # 将内容转化为unicode xmltodict 只支持unicode
        newparams = params_encoding(newparams)
        newparams['sign'] = sign
        xml_dict = {'xml': newparams}
        kwargs['data'] = smart_str(xmltodict.unparse(xml_dict))
        url = self._full_url(path)
        if self.mch_cert and self.mch_key:
            kwargs['cert'] = (self.mch_cert, self.mch_key)
        return method, url, kwargs

    # 统一下单
    # https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1 
示例4
def get_request_kwargs(self, api_params, *args, **kwargs):
        # stores kwargs prefixed with 'xmltodict_unparse__' for use by xmltodict.unparse
        self._xmltodict_unparse_kwargs = {k[len('xmltodict_unparse__'):]: kwargs.pop(k)
                                          for k in kwargs.copy().keys()
                                          if k.startswith('xmltodict_unparse__')}
        # stores kwargs prefixed with 'xmltodict_parse__' for use by xmltodict.parse
        self._xmltodict_parse_kwargs = {k[len('xmltodict_parse__'):]: kwargs.pop(k)
                                        for k in kwargs.copy().keys()
                                        if k.startswith('xmltodict_parse__')}

        arguments = super(XMLAdapterMixin, self).get_request_kwargs(
            api_params, *args, **kwargs)

        if 'headers' not in arguments:
            arguments['headers'] = {}
        arguments['headers']['Content-Type'] = 'application/xml'
        return arguments 
示例5
def test_xml_post_dict_passes_unparse_param(self):
        responses.add(responses.POST, self.wrapper.test().data,
                      body='Any response', status=200, content_type='application/json')

        data = OrderedDict([
            ('tag1', OrderedDict([
                ('@attr1', 'val1'), ('tag2', 'text1'), ('tag3', 'text2')
            ]))
        ])

        self.wrapper.test().post(data=data, xmltodict_unparse__full_document=False)

        request_body = responses.calls[0].request.body

        self.assertEqual(request_body, xmltodict.unparse(
            data, full_document=False).encode('utf-8')) 
示例6
def _prepare_blr_xml(self, restore_option):
        request_json = self._prepare_blr_json(restore_option)

        xml_string = xmltodict.unparse(request_json)
        plans = Plans(self._commcell_object)

        return (
            """<?xml version="1.0" encoding="UTF-8"?><EVGui_SetVMBlockLevelReplicationReq subclientId="{5}" opType="3">
            <blockLevelReplicationTaskXML><![CDATA[{0}]]></blockLevelReplicationTaskXML>
            <subClientProperties>
            <subClientEntity clientId="{1}" applicationId="106" instanceId="{2}" backupsetId="{3}"/>
            <planEntity planId="{4}"/>
            </subClientProperties>
            </EVGui_SetVMBlockLevelReplicationReq>
        """.format(
                xml_string,
                self._client_object.client_id,
                self._instance_object.instance_id,
                self._backupset_object.backupset_id,
                plans.all_plans[restore_option["plan_name"].lower()],
                self._subclient_id)) 
示例7
def change_video_settings(self, options):
        tilt = int((900 * int(options["brightness"])) / 100)
        pan = int((3600 * int(options["contrast"])) / 100)
        zoom = int((40 * int(options["hue"])) / 100)

        self.logger.info("Moving to %s:%s:%s", pan, tilt, zoom)
        req = {
            "PTZData": {
                "@version": "2.0",
                "@xmlns": "http://www.hikvision.com/ver20/XMLSchema",
                "AbsoluteHigh": {
                    "absoluteZoom": str(zoom),
                    "azimuth": str(pan),
                    "elevation": str(tilt),
                },
            }
        }
        self.cam.PTZCtrl.channels[1].absolute(
            method="put", data=xmltodict.unparse(req, pretty=True)
        ) 
示例8
def _generate_uvmpw_file(self):
        uvmpw_dic = xmltodict.parse(open(self.uvmpw_file, "rb"))
        uvmpw_dic['ProjectWorkspace']['project'] = []

        for project in self.workspace['projects']:
            # We check how far is project from root and workspace. IF they dont match,
            # get relpath for project and inject it into workspace
            path_project = os.path.dirname(project['files']['uvproj'])
            path_workspace = os.path.dirname(self.workspace['settings']['path'] + '\\')
            destination = os.path.join(os.path.relpath(self.env_settings.root, path_project), project['files']['uvproj'])
            if path_project != path_workspace:
                destination = os.path.join(os.path.relpath(self.env_settings.root, path_workspace), project['files']['uvproj'])
            uvmpw_dic['ProjectWorkspace']['project'].append({'PathAndName': destination})

        # generate the file
        uvmpw_xml = xmltodict.unparse(uvmpw_dic, pretty=True)
        project_path, uvmpw = self.gen_file_raw(uvmpw_xml, '%s.uvmpw' % self.workspace['settings']['name'], self.workspace['settings']['path'])
        return project_path, uvmpw 
示例9
def instruction_to_svg(self, instruction):
        """:return: an SVG representing the instruction.

        The SVG file is determined by the type attribute of the instruction.
        An instruction of type ``"knit"`` is looked for in a file named
        ``"knit.svg"``.

        Every element inside a group labeled ``"color"`` of mode ``"layer"``
        that has a ``"fill"`` style gets this fill replaced by the color of
        the instruction.
        Example of a recangle that gets filled like the instruction:

        .. code:: xml

            <g inkscape:label="color" inkscape:groupmode="layer">
                <rect style="fill:#ff0000;fill-opacity:1;fill-rule:nonzero"
                      id="rectangle1" width="10" height="10" x="0" y="0" />
            </g>

        If nothing was loaded to display this instruction, a default image is
        be generated by :meth:`default_instruction_to_svg`.
        """
        return xmltodict.unparse(self.instruction_to_svg_dict(instruction)) 
示例10
def send_properties(self, **kwargs):
		if not self._properties or 'ui_properties' not in self._properties:
			return

		# Decide the method to use.
		if self._instance.game.game == 'tm':
			method = 'Trackmania.UI.SetProperties'
		else:
			method = 'Shootmania.UI.SetProperties'

		# Create XML document
		try:
			xml = xd.unparse(self._properties, full_document=False, short_empty_elements=True)
		except Exception as e:
			logger.warning('Can\'t convert UI Properties to XML document! Error: {}'.format(str(e)))
			return

		try:
			await self._instance.gbx(method, xml, encode_json=False, response_id=False)
		except Exception as e:
			logger.warning('Can\'t send UI Properties! Error: {}'.format(str(e)))
			return 
示例11
def prepare_request(self, method, path, params):
        kwargs = {}
        _params = self.get_base_params()
        params.update(_params)
        newparams, prestr = params_filter(params)
        sign = build_mysign(prestr, self.partner_key)
        # 将内容转化为unicode xmltodict 只支持unicode
        newparams = params_encoding(newparams)
        newparams['sign'] = sign
        xml_dict = {'xml': newparams}
        kwargs['data'] = smart_str(xmltodict.unparse(xml_dict))
        url = self._full_url(path)
        if self.mch_cert and self.mch_key:
            kwargs['cert'] = (self.mch_cert, self.mch_key)
        return method, url, kwargs

    # 统一下单
    # https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1 
示例12
def prepare_request(self, method, path, params):
        kwargs = {}
        _params = self.get_base_params()
        params.update(_params)
        newparams, prestr = params_filter(params)
        sign = build_mysign(prestr, key=self.partner_key)
        # 将内容转化为unicode xmltodict 只支持unicode
        newparams = params_encoding(newparams)
        newparams['sign'] = sign
        xml_dict = {'xml': newparams}
        kwargs['data'] = smart_str(xmltodict.unparse(xml_dict))
        url = self._full_url(path)
        if self.mch_cert and self.mch_key:
            kwargs['cert'] = (self.mch_cert, self.mch_key)
        return method, url, kwargs

    # 统一下单
    # https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1 
示例13
def assertXMLEqual(self, expected, xml):
        expected = xmltodict.unparse(xmltodict.parse(expected))
        xml = xmltodict.unparse(xmltodict.parse(xml))
        self.assertEqual(expected, xml) 
示例14
def _output_convert(output_type, data):
    output_switch = {'dict': data,
                     'raw': data,
                     'json': json.dumps(data, indent=4),
                     'xml': xmltodict.unparse({'root': data})}
    return output_switch.get(output_type, None) 
示例15
def _update_subscribe(self, headers, raw_data):
        subscribers_url = "".join([self.url,
                                   "?oslc_cm.properties=rtc_cm:subscribers"])
        self.put(subscribers_url,
                 verify=False,
                 proxies=self.rtc_obj.proxies,
                 headers=headers,
                 data=xmltodict.unparse(raw_data)) 
示例16
def make_shape(name, points):
    ''' Make the STL and XML, and save both to the proper directories. '''
    # Make the STL and XML
    shape, size = build_stl(name, points)
    xml_dict = build_xml(name, size)
    # Make the directory to save files to if we have to
    xml_dirname = worldgen_path('assets', 'xmls', 'shapes', name)
    stl_dirname = worldgen_path('assets', 'stls', 'shapes', name)
    os.makedirs(xml_dirname, exist_ok=True)
    os.makedirs(stl_dirname, exist_ok=True)
    # Save the STL and XML to our new directories
    shape.save(os.path.join(stl_dirname, name + '.stl'))
    with open(os.path.join(xml_dirname, 'main.xml'), 'w') as f:
        f.write(xmltodict.unparse(xml_dict, pretty=True)) 
示例17
def unparse_dict(xml_dict):
    '''
    Convert a normalized XML dictionary into a XML string.  See stringify().
    Note: this modifies xml_dict in place to have strings instead of values.
    '''
    stringify(xml_dict)
    xml_doc_dict = OrderedDict(mujoco=xml_dict)
    return xmltodict.unparse(xml_doc_dict, pretty=True) 
示例18
def send_xml_request(url, param):
    # dict 2 xml
    param = {'root': param}
    xml = xmltodict.unparse(param)

    response = requests.post(url, data=xml.encode('utf-8'), headers={'Content-Type': 'text/xml'})
    # xml 2 dict
    msg = response.text
    xmlmsg = xmltodict.parse(msg)

    return xmlmsg

# 统一下单 
示例19
def write_document(document, out, validate=True):

    if validate:
        messages = []
        messages = document.validate(messages)
        if messages:
            raise InvalidDocumentError(messages)

    writer = Writer(document)
    document_object = {'SpdxDocument': writer.create_document()}

    xmltodict.unparse(document_object, out, encoding='utf-8', pretty=True) 
示例20
def attach_devices(self, devs: List[dict]):
        for ids in devs:
            dev = self.get_device_by_ids(ids)
            if dev is None:
                dev = xmltodict.unparse({
                    "hostdev": {
                        "@mode": "subsystem",
                        "@type": "usb",
                        "source": {
                            "vendor": {"@id": hex(ids[0])},
                            "product": {"@id": hex(ids[1])}
                        }
                    }
                })
                self._dom.attachDevice(dev) 
示例21
def detach_devices(self, devs: List[dict]):
        for dev in self.get_devices():
            if self.get_device_ids(dev) in devs:
                xml = xmltodict.unparse({"hostdev": dev})
                self._dom.detachDevice(xml) 
示例22
def _input_branches_to_xml_bytestring(self, data):
        if isinstance(data, Mapping):
            return xmltodict.unparse(
                data, **self._xmltodict_unparse_kwargs).encode('utf-8')
        try:
            return data.encode('utf-8')
        except Exception as e:
            raise type(e)('Format not recognized, please enter an XML as string or a dictionary'
                          'in xmltodict spec: \n%s' % e.message) 
示例23
def test_xml_post_dict(self):
        responses.add(responses.POST, self.wrapper.test().data,
                      body='Any response', status=200, content_type='application/json')

        data = OrderedDict([
            ('tag1', OrderedDict([
                ('@attr1', 'val1'), ('tag2', 'text1'), ('tag3', 'text2')
            ]))
        ])

        self.wrapper.test().post(data=data)

        request_body = responses.calls[0].request.body

        self.assertEqual(request_body, xmltodict.unparse(data).encode('utf-8')) 
示例24
def _send_xml(self, request_dict):
        """Sends the boot request xml"""
        xml_payload = xmltodict.unparse(request_dict)
        response = self._commcell.execute_qcommand("qoperation execute", xml_payload)

        try:
            return response.json()["jobIds"][0]
        except (KeyError, JSONDecodeError) as error:
            raise SDKException("Backupset", 102,
                               "Boot was not successful. %s" % response.json().get("errorMessage", "")) from error 
示例25
def to_string(self):
        '''
        generate an XML string from this dictionary

        :return: XML string
        '''
        import xmltodict
        tmp = {'parameters': CodeParameters()}
        tmp['parameters'].update(copy.deepcopy(self))
        recursive_encoder(tmp)
        return xmltodict.unparse(tmp, pretty=True) 
示例26
def write_xml(self, filename):
        outfile = open(filename, "w")
        outfile.write(xmltodict.unparse(self.doc, pretty=True)) 
示例27
def __str__(self):
        if self.doc is None:
            return ""
        else:
            return xmltodict.unparse(self.doc, pretty=True) 
示例28
def search(self, num_attempts=1, sleep_time=0.5):
        """
        Perform a search of the Protein Data Bank using the REST API
        
        Parameters
        ----------

        num_attempts : int
            In case of a failed retrieval, the number of attempts to try again
        sleep_time : int
            The amount of time to wait between requests, in case of 
            API rate limits
        """

        queryText = xmltodict.unparse(self.scan_params, pretty=False)
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        #response = requests.post(self.url, data=queryText, headers=headers)
        response = post_limited(self.url, data=queryText, headers=headers)

        if response.status_code == 200:
            pass
        else:
            warnings.warn("Retrieval failed, returning None")
            return None

        result  = response.text

        idlist = str(result)
        idlist = idlist.split('\n')[:-1]

        return idlist


# functions for conducting searches and obtaining lists of PDB ids 
示例29
def _generate_eww_file(self):
        eww_dic = xmltodict.parse(open(self.eww_file).read())
        self._eww_set_path_multiple_project(eww_dic)

        # generate the file
        eww_xml = xmltodict.unparse(eww_dic, pretty=True)
        project_path, eww = self.gen_file_raw(eww_xml, '%s.eww' % self.workspace['settings']['name'], self.workspace['settings']['path'])
        return project_path, [eww] 
示例30
def _generate_vcxproj_files(self, proj_dict, name, rel_path, vcxproj_user_dic):
        output = copy.deepcopy(self.generated_project)
        project_path, output['files']['vcxproj.filters'] = self.gen_file_jinja(
            'visual_studio.vcxproj.filters.tmpl', proj_dict, '%s.vcxproj.filters' % name, rel_path)
        project_path, output['files']['vcxproj'] = self.gen_file_jinja(
            'visual_studio.vcxproj.tmpl', proj_dict, '%s.vcxproj' % name, rel_path)
        project_path, output['files']['vcxproj.user'] = self.gen_file_raw(
            xmltodict.unparse(vcxproj_user_dic, pretty=True), '%s.vcxproj.user' % name, rel_path)
        return project_path, output