Python xmltodict.unparse() Examples

The following are 30 code examples of xmltodict.unparse(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module xmltodict , or try the search function .
Example #1
Source File: hikvision.py    From unifi-cam-proxy with MIT License 6 votes vote down vote up
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)
        ) 
Example #2
Source File: pay.py    From wechat_mall with MIT License 6 votes vote down vote up
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 
Example #3
Source File: pay.py    From wechat_mall with MIT License 6 votes vote down vote up
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 
Example #4
Source File: uvision.py    From project_generator with Apache License 2.0 6 votes vote down vote up
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 
Example #5
Source File: withdraw_demo.py    From weixin_demo with MIT License 6 votes vote down vote up
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 
Example #6
Source File: ui_properties.py    From PyPlanet with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #7
Source File: pay.py    From -Odoo--- with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #8
Source File: pay.py    From -Odoo--- with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #9
Source File: InstructionToSVG.py    From knittingpattern with GNU Lesser General Public License v3.0 6 votes vote down vote up
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)) 
Example #10
Source File: adapters.py    From tapioca-wrapper with MIT License 6 votes vote down vote up
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 
Example #11
Source File: vssubclient.py    From cvpysdk with Apache License 2.0 6 votes vote down vote up
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)) 
Example #12
Source File: test_tapioca.py    From tapioca-wrapper with MIT License 6 votes vote down vote up
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')) 
Example #13
Source File: InstructionToSVG.py    From knittingpattern with GNU Lesser General Public License v3.0 5 votes vote down vote up
def default_instruction_to_svg(self, instruction):
        """As :meth:`instruction_to_svg` but it only takes the ``default.svg``
        file into account.

        In case no file is found for an instruction in
        :meth:`instruction_to_svg`,
        this method is used to determine the default svg for it.

        The content is created by replacing the text ``{instruction.type}`` in
        the whole svg file named ``default.svg``.

        If no file ``default.svg`` was loaded, an empty string is returned.
        """
        svg_dict = self.default_instruction_to_svg_dict(instruction)
        return xmltodict.unparse(svg_dict) 
Example #14
Source File: iar.py    From project_generator with Apache License 2.0 5 votes vote down vote up
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] 
Example #15
Source File: visual_studio.py    From project_generator with Apache License 2.0 5 votes vote down vote up
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 
Example #16
Source File: visual_studio.py    From project_generator with Apache License 2.0 5 votes vote down vote up
def export_project(self):
        output = copy.deepcopy(self.generated_project)
        expanded_dic = self.workspace.copy()

        # data for .vcxproj
        expanded_dic['vcxproj'] = {}
        expanded_dic['vcxproj'] = self._set_vcxproj(expanded_dic['name'])

        # data for debugger for pyOCD
        expanded_dic['vcxproj_user'] = {}
        # TODO: localhost and gdb should be misc for VS ! Add misc options
        vcxproj_user_dic = self._set_vcxproj_user('localhost:3333', 'arm-none-eabi-gdb',
            os.path.join(expanded_dic['build_dir'], expanded_dic['name']), os.path.join(os.getcwd(), expanded_dic['output_dir']['path']))

        self._set_groups(expanded_dic)

        # Project files
        project_path, output = self._generate_vcxproj_files(expanded_dic, 
            expanded_dic['name'], expanded_dic['output_dir']['path'], vcxproj_user_dic)

        # NMake and debugger assets
        # TODO: not sure about base class having NMake and debugger. We might want to disable that by default?
        self.gen_file_raw(xmltodict.unparse(self.linux_nmake_xaml, pretty=True), 'linux_nmake.xaml', expanded_dic['output_dir']['path'])
        self.gen_file_raw(xmltodict.unparse(self.linux_debugger_xaml, pretty=True), 'LocalDebugger.xaml', expanded_dic['output_dir']['path'])

        return output 
Example #17
Source File: visual_studio.py    From project_generator with Apache License 2.0 5 votes vote down vote up
def export_project(self):
        output = copy.deepcopy(self.generated_project)
        data_for_make = self.workspace.copy()

        self.exporter.process_data_for_makefile(data_for_make)
        output['path'], output['files']['makefile'] = self.gen_file_jinja('makefile_gcc.tmpl', data_for_make, 'Makefile', data_for_make['output_dir']['path'])

        expanded_dic = self.workspace.copy()

        expanded_dic['makefile'] = True

        # data for .vcxproj
        expanded_dic['vcxproj'] = {}
        expanded_dic['vcxproj'] = self._set_vcxproj(expanded_dic['name'],'make all', 'make clean &amp;&amp; make all',
            'make clean &amp;&amp; make all', '')

        # data for debugger for pyOCD
        expanded_dic['vcxproj_user'] = {}
        # TODO: localhost and gdb should be misc for VS ! Add misc options
        vcxproj_user_dic = self._set_vcxproj_user('localhost:3333', 'arm-none-eabi-gdb',
            os.path.join(expanded_dic['build_dir'], expanded_dic['name']), os.path.join(os.getcwd(), data_for_make['output_dir']['path']))

        self._set_groups(expanded_dic)

        # Project files
        project_path, vcx_files = self._generate_vcxproj_files(expanded_dic, expanded_dic['name'], 
            data_for_make['output_dir']['path'], vcxproj_user_dic)
        output['files']['vcxproj.filters'] = vcx_files['files']['vcxproj.filters']
        output['files']['vcxproj'] = vcx_files['files']['vcxproj']
        output['files']['vcxproj.user'] = vcx_files['files']['vcxproj.user']

        # NMake and debugger assets
        self.gen_file_raw(xmltodict.unparse(self.linux_nmake_xaml, pretty=True), 'linux_nmake.xaml', data_for_make['output_dir']['path'])
        self.gen_file_raw(xmltodict.unparse(self.linux_debugger_xaml, pretty=True), 'LocalDebugger.xaml', data_for_make['output_dir']['path'])

        return output 
Example #18
Source File: SVGBuilder.py    From knittingpattern with GNU Lesser General Public License v3.0 5 votes vote down vote up
def write_to_file(self, file):
        """Writes the current SVG to the :paramref:`file`.

        :param file: a file-like object
        """
        xmltodict.unparse(self._structure, file, pretty=True) 
Example #19
Source File: xmlprofile.py    From hifiberry-dsp with MIT License 5 votes vote down vote up
def write_xml(self, filename):
        outfile = open(filename, "w")
        outfile.write(xmltodict.unparse(self.doc, pretty=True)) 
Example #20
Source File: xml.py    From knittingpattern with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _dump_to_file(self, file):
        """dump to the file"""
        xmltodict.unparse(self.object(), file, pretty=True) 
Example #21
Source File: wc.py    From tushe with MIT License 5 votes vote down vote up
def xml_response(data):
    d = {'xml': data}
    return xmltodict.unparse(d) 
Example #22
Source File: xml.py    From dataknead with MIT License 5 votes vote down vote up
def write(f, data, pretty = True):
        xmldata = xmltodict.unparse(data, pretty = pretty)
        f.write(xmldata) 
Example #23
Source File: configuration.py    From PiModules with GNU General Public License v3.0 5 votes vote down vote up
def write_config_xml(xmlfile, dict):
	try:
	        with open(xmlfile, "wt") as fo:
	                xmltodict.unparse(dict, fo, pretty=True)
	except IOError as e:
		print "Error writing XML file: ", e
		return False

	return True 
Example #24
Source File: __init__.py    From virtkvm with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #25
Source File: Serializer.py    From django-angularjs-blog with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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) 
Example #26
Source File: workitem.py    From rtcclient with Apache License 2.0 5 votes vote down vote up
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)) 
Example #27
Source File: make_shape.py    From mujoco-worldgen with MIT License 5 votes vote down vote up
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)) 
Example #28
Source File: parser.py    From mujoco-worldgen with MIT License 5 votes vote down vote up
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) 
Example #29
Source File: pay_demo.py    From weixin_demo with MIT License 5 votes vote down vote up
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

# 统一下单 
Example #30
Source File: xml.py    From tools-python with Apache License 2.0 5 votes vote down vote up
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)