本文整理汇总了Python中xmltodict.unparse函数的典型用法代码示例。如果您正苦于以下问题:Python unparse函数的具体用法?Python unparse怎么用?Python unparse使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了unparse函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_generator
def test_generator(self):
obj = {'a': {'b': ['1', '2', '3']}}
def lazy_obj():
return {'a': {'b': (i for i in ('1', '2', '3'))}}
self.assertEqual(obj, parse(unparse(lazy_obj())))
self.assertEqual(unparse(lazy_obj()),
unparse(parse(unparse(lazy_obj()))))
示例2: write
def write(path, doc, unix=False):
# Convert items to list
doc['anime-list']['anime'] = doc['anime-list']['anime'].values()
# Encode document
buf = StringIO()
unparse(
doc,
output=buf,
indent=' ',
newl='\n',
pretty=True,
short_empty_elements=True
)
# Convert to string
data = buf.getvalue() + '\n'
if unix:
data = data.replace('\n', '\r\n')
# Write data to path
with open(path, 'w') as fp:
fp.write(data)
示例3: test_multiple_roots_nofulldoc
def test_multiple_roots_nofulldoc(self):
obj = OrderedDict((('a', 1), ('b', 2)))
xml = unparse(obj, full_document=False)
self.assertEqual(xml, '<a>1</a><b>2</b>')
obj = {'a': [1, 2]}
xml = unparse(obj, full_document=False)
self.assertEqual(xml, '<a>1</a><a>2</a>')
示例4: make_qbxml
def make_qbxml(self, query=None, payload=None):
"""
Outputs a valid QBXML
if there is a payload it will be included in the output
:param query is the full name of the object like CustomerAddRq
:param payload is the optional payload , it is required when adding items.
"""
if payload:
qb_request = payload
else:
qb_request = None
qbxml_query = {
'QBXML': {
'QBXMLMsgsRq':
{
'@onError': "stopOnError",
query: qb_request
}
}
}
data_xml = self.xml_soap(xmltodict.unparse(qbxml_query, full_document=False))
data_xml = xmltodict.unparse(qbxml_query, full_document=False)
res = self.xml_prefix + data_xml
return res
示例5: export_project
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
示例6: StaticDiscovery
def StaticDiscovery():
"""
"""
p = Associate()
for obisInfo in OBISList:
a = obisInfo['code'][0]
b = obisInfo['code'][1]
c = obisInfo['code'][2]
d = obisInfo['code'][3]
e = obisInfo['code'][4]
f = obisInfo['code'][5]
ic = int(obisInfo['ic'])
hexCode = '%02x%02x%02x%02x%02x%02x'%(a,b,c,d,e,f)
print('------- getting %s ic=%d --------'%(hexCode,ic))
if ic == 3:
rq = DLMSPlayground.CreateGetRequest(ic,hexCode,3)
elif ic == 4:
rq = DLMSPlayground.CreateGetRequest(ic,hexCode,4)
elif ic == 5:
rq = DLMSPlayground.CreateGetRequest(ic,hexCode,4)
elif ic == 8:
rq = DLMSPlayground.CreateGetRequest(ic,hexCode,3)
elif ic == 1:
rq = DLMSPlayground.CreateGetRequest(ic,hexCode,3)
else:
print('oops...')
pass
print(rq)
DLMSPlayground.SendHDLCToMeter(p, rq )
time.sleep(0.5)
rsp = DLMSPlayground.GetResponseFromMeter(p)
print(rsp)
print( DLMS.HDLCToDict(rsp) )
if rsp != None:
xmlAttr3 = xmltodict.unparse(DLMS.HDLCToDict(rsp))
rq = DLMSPlayground.CreateGetRequest(ic,hexCode,2)
print(rq)
DLMSPlayground.SendHDLCToMeter(p, rq )
time.sleep(0.5)
rsp = DLMSPlayground.GetResponseFromMeter(p)
print(rsp)
print( DLMS.HDLCToDict(rsp) )
if rsp != None:
xmlAttr2 = xmltodict.unparse(DLMS.HDLCToDict(rsp))
combinedXML = '<Object><OBIS value="%s" /><ClassID Value="%d" /><Attribute2Read>%s</Attribute2Read>\n<Attribute3Read>%s</Attribute3Read></Object>'%(hexCode,ic,xmlAttr2,xmlAttr3)
combinedXML = re.sub(r'<\?.*\?>','',combinedXML)
open('Objects/%s.xml'%(hexCode),'w+').write(combinedXML)
示例7: write_config_xml
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
示例8: check_notify
def check_notify(self, xml_notify, handle):
self._logResp(xml_notify, 'Wechat pay notify')
content = self._check_error(xml_notify)
result, fail_msg = handle(**content)
if result:
return unparse(dict(xml={'return_code': 'SUCCESS'}))
else:
self.log.error('Wechat pay notify fail: {}'.format(fail_msg))
return unparse(dict(xml={'return_code': 'FAIL', 'return_msg': fail_msg}))
示例9: test_encoding
def test_encoding(self):
try:
value = unichr(39321)
except NameError:
value = chr(39321)
obj = {'a': value}
utf8doc = unparse(obj, encoding='utf-8')
latin1doc = unparse(obj, encoding='iso-8859-1')
self.assertEqual(parse(utf8doc), parse(latin1doc))
self.assertEqual(parse(utf8doc), obj)
示例10: _api_out_as
def _api_out_as(self, out):
""" Formats the response to the desired output """
if self._api_cmd == "docs_md":
return out["response"]["data"]
elif self._api_cmd == "download_log":
return
elif self._api_cmd == "pms_image_proxy":
cherrypy.response.headers["Content-Type"] = "image/jpeg"
return out["response"]["data"]
if self._api_out_type == "json":
cherrypy.response.headers["Content-Type"] = "application/json;charset=UTF-8"
try:
if self._api_debug:
out = json.dumps(out, indent=4, sort_keys=True)
else:
out = json.dumps(out)
if self._api_callback is not None:
cherrypy.response.headers["Content-Type"] = "application/javascript"
# wrap with JSONP call if requested
out = self._api_callback + "(" + out + ");"
# if we fail to generate the output fake an error
except Exception as e:
logger.info(u"PlexPy APIv2 :: " + traceback.format_exc())
out["message"] = traceback.format_exc()
out["result"] = "error"
elif self._api_out_type == "xml":
cherrypy.response.headers["Content-Type"] = "application/xml"
try:
out = xmltodict.unparse(out, pretty=True)
except Exception as e:
logger.error(u"PlexPy APIv2 :: Failed to parse xml result")
try:
out["message"] = e
out["result"] = "error"
out = xmltodict.unparse(out, pretty=True)
except Exception as e:
logger.error(u"PlexPy APIv2 :: Failed to parse xml result error message %s" % e)
out = (
"""<?xml version="1.0" encoding="utf-8"?>
<response>
<message>%s</message>
<data></data>
<result>error</result>
</response>
"""
% e
)
return out
示例11: test_multiple_roots
def test_multiple_roots(self):
try:
unparse({'a': '1', 'b': '2'})
self.fail()
except ValueError:
pass
try:
unparse({'a': ['1', '2', '3']})
self.fail()
except ValueError:
pass
示例12: convert
def convert(self, path, data):
if isinstance(data, list):
data = {'items': {str(k): v for k, v in enumerate(data)}}
try:
with open(path, 'w') as outfile:
xmltodict.unparse(data, outfile, pretty=True)
except Exception:
logger.exception(u'File `{}` can not be parsed in xml'.format(path))
os.remove(path)
raise
return path
示例13: _api_out_as
def _api_out_as(self, out):
""" Formats the response to the desired output """
if self._api_cmd == 'docs_md':
return out['response']['data']
elif self._api_cmd == 'download_log':
return
elif self._api_cmd == 'pms_image_proxy':
cherrypy.response.headers['Content-Type'] = 'image/jpeg'
return out['response']['data']
if self._api_out_type == 'json':
cherrypy.response.headers['Content-Type'] = 'application/json;charset=UTF-8'
try:
if self._api_debug:
out = json.dumps(out, indent=4, sort_keys=True)
else:
out = json.dumps(out)
if self._api_callback is not None:
cherrypy.response.headers['Content-Type'] = 'application/javascript'
# wrap with JSONP call if requested
out = self._api_callback + '(' + out + ');'
# if we fail to generate the output fake an error
except Exception as e:
logger.info(u'PlexPy APIv2 :: ' + traceback.format_exc())
out['message'] = traceback.format_exc()
out['result'] = 'error'
elif self._api_out_type == 'xml':
cherrypy.response.headers['Content-Type'] = 'application/xml'
try:
out = xmltodict.unparse(out, pretty=True)
except Exception as e:
logger.error(u'PlexPy APIv2 :: Failed to parse xml result')
try:
out['message'] = e
out['result'] = 'error'
out = xmltodict.unparse(out, pretty=True)
except Exception as e:
logger.error(u'PlexPy APIv2 :: Failed to parse xml result error message %s' % e)
out = '''<?xml version="1.0" encoding="utf-8"?>
<response>
<message>%s</message>
<data></data>
<result>error</result>
</response>
''' % e
return out
示例14: __call__
def __call__(self, text):
soap_version = None
try:
data = xmltodict.parse(text, process_namespaces=True,
namespaces=self.parse_ns)
if "s11:Envelope" in data:
soap_version = SOAP11
body = data["s11:Envelope"]["s11:Body"]
elif "s12:Envelope" in data:
soap_version = SOAP12
body = data["s12:Envelope"]["s12:Body"]
else:
if self.ctx:
self.ctx.exc_info = None
self.ctx.error = True
return "Missing SOAP Envelope"
res = self.app(body)
out = OrderedDict([
("env:Envelope", OrderedDict([
("@xmlns:env", soap_version),
("env:Body", res),
])),
])
# Add namespace attributes, preferably to the inner top-level element
# but fallback to putting them on the Envelope
root = out["env:Envelope"]
try:
keys = res.keys()
if len(keys) == 1:
root = res[keys[0]]
except AttributeError:
pass
for (k, v) in self.namespaces.iteritems():
root["@xmlns:"+v] = k
# Add canned attributes, typically for adding encodingStyle
# (Note: SOAP 1.1 allows this to be anywhere including on the
# envelope, but SOAP 1.2 is more restrictive)
if self.reply_attrs:
root.update(self.reply_attrs)
return xmltodict.unparse(out, **self.unparse_options)
except Exception:
if not self.trap_exception: raise
exc_info = sys.exc_info()
if self.ctx:
# This allows the exception to be logged elsewhere,
# and for a HTTP connector to return a 500 status code
self.ctx.exc_info = exc_info
self.ctx.error = True
return xmltodict.unparse(self.fault(exc_info, soap_version),
**self.unparse_options)
示例15: test_nested
def test_nested(self):
obj = {"a": {"b": "1", "c": "2"}}
self.assertEqual(obj, parse(unparse(obj)))
self.assertEqual(unparse(obj), unparse(parse(unparse(obj))))
obj = {"a": {"b": {"c": {"@a": "x", "#text": "y"}}}}
self.assertEqual(obj, parse(unparse(obj)))
self.assertEqual(unparse(obj), unparse(parse(unparse(obj))))