本文整理汇总了Python中dicttoxml.dicttoxml方法的典型用法代码示例。如果您正苦于以下问题:Python dicttoxml.dicttoxml方法的具体用法?Python dicttoxml.dicttoxml怎么用?Python dicttoxml.dicttoxml使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类dicttoxml
的用法示例。
在下文中一共展示了dicttoxml.dicttoxml方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: module_run
# 需要导入模块: import dicttoxml [as 别名]
# 或者: from dicttoxml import dicttoxml [as 别名]
def module_run(self):
filename = self.options['filename']
with codecs.open(filename, 'wb', encoding='utf-8') as outfile:
# build a list of table names
tables = [x.strip() for x in self.options['tables'].split(',')]
data_dict = {}
cnt = 0
for table in tables:
data_dict[table] = []
columns = [x[0] for x in self.get_columns(table)]
columns_str = '", "'.join(columns)
rows = self.query(f'SELECT "{columns_str}" FROM "{table}" ORDER BY 1')
for row in rows:
row_dict = {}
for i in range(0, len(columns)):
row_dict[columns[i]] = row[i]
data_dict[table].append(row_dict)
cnt += 1
# write the xml to a file
reparsed = parseString(dicttoxml(data_dict))
outfile.write(reparsed.toprettyxml(indent=' '*4))
self.output(f"{cnt} records added to '{filename}'.")
示例2: render
# 需要导入模块: import dicttoxml [as 别名]
# 或者: from dicttoxml import dicttoxml [as 别名]
def render(self, data, accepted_media_type=None, renderer_context=None):
# data should be str, but in case it's a dict, return as XML.
# e.g. It happens with 404
if isinstance(data, dict):
# Force cast `ErrorDetail` as `six.text_type` because `dicttoxml`
# does not recognize this type and treat each character as xml node.
for k, v in data.items():
if isinstance(v, ErrorDetail):
data[k] = str(v)
# FIXME new `v2` list endpoint enters this block
# Submissions are wrapped in `<item>` nodes.
return dicttoxml(data, attr_type=False)
if renderer_context.get("view").action == "list":
return "<root>{}</root>".format("".join(data))
else:
return data
示例3: get_results
# 需要导入模块: import dicttoxml [as 别名]
# 或者: from dicttoxml import dicttoxml [as 别名]
def get_results(self):
pathlib.Path('./output/').mkdir(parents=True, exist_ok=True)
if(self.output_format == "xml"):
xml = dicttoxml(self.final_results, attr_type=False)
f = open(self.output_file, "wb")
f.write(xml)
f.close()
else:
try:
if(self.args["adapt_general"]["append"] == True and os.path.isfile(self.output_file)):
with open(self.output_file, "r") as f:
d = json.load(f)
f.close()
d += self.final_results
self.final_results = d
with open(self.output_file, "w") as f:
json.dump(self.final_results, f, indent=4)
f.close()
except Exception as e:
with open(self.backup, "w") as f:
json.dump(self.final_results, f, indent=4)
f.close()
示例4: module_run
# 需要导入模块: import dicttoxml [as 别名]
# 或者: from dicttoxml import dicttoxml [as 别名]
def module_run(self):
filename = self.options['filename']
with codecs.open(filename, 'wb', encoding='utf-8') as outfile:
# build a list of table names
tables = [x.strip() for x in self.options['tables'].split(',')]
data_dict = {}
cnt = 0
for table in tables:
data_dict[table] = []
columns = [x[0] for x in self.get_columns(table)]
rows = self.query('SELECT "%s" FROM "%s" ORDER BY 1' % ('", "'.join(columns), table))
for row in rows:
row_dict = {}
for i in range(0,len(columns)):
row_dict[columns[i]] = row[i]
data_dict[table].append(row_dict)
cnt += 1
# write the xml to a file
reparsed = parseString(dicttoxml(data_dict))
outfile.write(reparsed.toprettyxml(indent=' '*4))
self.output('%d records added to \'%s\'.' % (cnt, filename))
示例5: process
# 需要导入模块: import dicttoxml [as 别名]
# 或者: from dicttoxml import dicttoxml [as 别名]
def process(self, data):
super(DeenPluginJsonToXmlFormatter, self).process(data)
if not DICTTOXML:
return
try:
data = json.loads(data.decode())
except (json.JSONDecodeError, TypeError,
UnicodeDecodeError, AssertionError) as e:
self.error = e
self.log.error(self.error)
self.log.debug(self.error, exc_info=True)
return
try:
data = dicttoxml.dicttoxml(data)
except Exception as e:
self.error = e
self.log.error(self.error)
self.log.debug(self.error, exc_info=True)
return data
示例6: xml_formatter
# 需要导入模块: import dicttoxml [as 别名]
# 或者: from dicttoxml import dicttoxml [as 别名]
def xml_formatter(result, _verbose):
"""Format result as xml."""
return parseString(dicttoxml(result)).toprettyxml()
示例7: bad_request
# 需要导入模块: import dicttoxml [as 别名]
# 或者: from dicttoxml import dicttoxml [as 别名]
def bad_request(error):
message = {'Error': error[1], 'Status Code': error[0]}
response = dicttoxml(message) if error[2] == 'xml' else json.dumps(message)
return make_response(response, error[0])
示例8: to_xml
# 需要导入模块: import dicttoxml [as 别名]
# 或者: from dicttoxml import dicttoxml [as 别名]
def to_xml(self, filename):
with open(filename, 'wb') as f:
f.write(b'<?xml version="1.0" encoding="UTF-8"?><items>')
for element in self.data:
xml = dicttoxml(element, custom_root='item', attr_type=False)\
.replace(b'<?xml version="1.0" encoding="UTF-8" ?>', b'')
f.write(xml)
f.write(b'</items>')
示例9: dict_to_xml
# 需要导入模块: import dicttoxml [as 别名]
# 或者: from dicttoxml import dicttoxml [as 别名]
def dict_to_xml(dict):
"""Convert dict to xml.
Args:
dict (dict): Dictionary.
Returns:
str: Return a XML representation of an dict.
"""
return dicttoxml(dict).decode()
示例10: xmlify
# 需要导入模块: import dicttoxml [as 别名]
# 或者: from dicttoxml import dicttoxml [as 别名]
def xmlify(rows):
'''Expects a list of dictionaries and returns a XML response.'''
xml = dicttoxml([dict(r) for r in rows])
return Response(xml, mimetype='text/xml')
示例11: xml
# 需要导入模块: import dicttoxml [as 别名]
# 或者: from dicttoxml import dicttoxml [as 别名]
def xml(func):
"""
Decorator to render as XML
:param func:
:return:
"""
if inspect.isclass(func):
apply_function_to_members(func, xml)
return func
else:
@functools.wraps(func)
def decorated_view(*args, **kwargs):
data = func(*args, **kwargs)
return _build_response(data, dicttoxml)
return decorated_view
示例12: format_xml
# 需要导入模块: import dicttoxml [as 别名]
# 或者: from dicttoxml import dicttoxml [as 别名]
def format_xml(data, root, lst=list(), parent_child=False):
"""将dict转换为xml, xml_config是一个bytes"""
if parent_child:
xml_config = dicttoxml(data, item_func=lambda x: x[:-1], custom_root=root, attr_type=False)
else:
xml_config = dicttoxml(data, item_func=lambda x: x, custom_root=root, attr_type=False)
for i in lst:
xml_config = xml_config.replace(to_bytes(i+i), to_bytes(i))
return xml_config
示例13: to_xml
# 需要导入模块: import dicttoxml [as 别名]
# 或者: from dicttoxml import dicttoxml [as 别名]
def to_xml(self) -> str:
"""
Экспорт в XML.
:return self: строка в формате XML
"""
return dicttoxml(self.to_dict(), custom_root='markup', attr_type=False).decode('utf-8').replace("\n", "\\n")
示例14: format
# 需要导入模块: import dicttoxml [as 别名]
# 或者: from dicttoxml import dicttoxml [as 别名]
def format(self, item):
import dicttoxml
dicttoxml.LOG.setLevel(logging.WARNING)
fields_len = len(self.fields_order)
ordered_item = collections.OrderedDict(
sorted(item.items(),
key=lambda kv: self.fields_order.get(kv[0], fields_len))
)
return '<{0}>{1}</{0}>'.format(
self.item_name, dicttoxml.dicttoxml(ordered_item, root=False,
attr_type=self.attr_type))
示例15: xmind_to_xml
# 需要导入模块: import dicttoxml [as 别名]
# 或者: from dicttoxml import dicttoxml [as 别名]
def xmind_to_xml(file_path):
try:
from dicttoxml import dicttoxml
from xml.dom.minidom import parseString
target = _get_out_file_name(file_path, 'xml')
xml = dicttoxml(xmind_to_dict(file_path), custom_root='root')
xml = parseString(xml.decode('utf8')).toprettyxml(encoding='utf8')
with open(target, 'w', encoding='utf8') as f:
f.write(xml.decode('utf8'))
return target
except ImportError:
raise ImportError('Parse xmind to xml require "dicttoxml", try install via pip:\n' +
'> pip install dicttoxml')