Форум сайта python.su
Всем привет,
есть несколько файлов с похожим кодом,
отличаются только названиями полей м значениями в etree.SubElement.
Вопрос, можно ли как-то превратить это в один класс и чтобы было красиво?
Самая суть, что в каждом таком файле названия полей и строки из базы разные.
Намекните чем-нибудь, Спасибо.
root = etree.Element("CityList", ExportDate="2016-12-05T17:55:55")
data = sql_exec('select * from city')
for r in data:
etree.SubElement(
root,
"city",
id=str(r[0]),
guid=str(r[0]),
name=u'%s' % r[2],
flagDeleted=u'N',
country=str(r[1]),
region=str(r[3]),
isDistrict=u'N',
)
xml = etree.tostring(
root,
pretty_print = True,
xml_declaration = True,
encoding='UTF-8',
standalone="yes"
)
with open('city.xml', 'w') as f:
f.write(xml)
Офлайн
def f(element, expdate, table): root = etree.Element(element, ExportDate=expdate) data = sql_exec('select * from ' + table) for r in data: etree.SubElement( root, table, id=str(r[0]), guid=str(r[0]), name=u'%s' % r[2], flagDeleted=u'N', country=str(r[1]), region=str(r[3]), isDistrict=u'N', ) xml = etree.tostring( root, pretty_print = True, xml_declaration = True, encoding='UTF-8', standalone="yes" ) with open(table + '.xml', 'w') as f: f.write(xml) f('CityList', '2016-12-05T17:55:55', 'city')
Офлайн
py.user.nextвопрос именно в этой структуре, а разных файлах она разная, как-то хочется абстрактно передавать название колонки и поле из базы и формировать такие структуры для разных файлов.
root,
table,
id=str(r),
guid=str(r),
name=u'%s' % r,
flagDeleted=u'N',
country=str(r),
region=str(r),
isDistrict=u'N',
root,
table,
id=str(r[0]),
guid=str(r[0]),
name=u'%s' % r[2],
flagDeleted=u'N',
country=str(r[1]),
region=str(r[3]),
isDistrict=u'N',
Отредактировано xammett (Янв. 13, 2017 23:36:52)
Офлайн
Ну, приведи несколько файлов, а то непонятно, что ты хочешь, то одно пишешь, то другое.
xammett
Самая суть, что в каждом таком файле названия полей и строки из базы разные.
xammett
абстрактно передавать название колонки и поле из базы
Офлайн
py.user.next
Ну, приведи несколько файлов, а то непонятно, что ты хочешь, то одно пишешь, то другое.
root = etree.Element("CityList", ExportDate="2016-12-05T17:55:55")
data = sql_exec('select * from city')
for r in data:
etree.SubElement(
root,
"city",
id=str(r[0]),
guid=str(r[0]),
name=u'%s' % r[2],
flagDeleted=u'N',
country=str(r[1]),
region=str(r[3]),
isDistrict=u'N',
)
xml = etree.tostring(
root,
pretty_print = True,
xml_declaration = True,
encoding='UTF-8',
standalone="yes"
)
with open('city.xml', 'w') as f:
f.write(xml)
root = etree.Element("BrandList", ExportDate="2016-12-05T17:55:55")
data = sql_exec('select * from brand')
for r in data:
etree.SubElement(
root,
"brand",
id=str(r[0]),
shortName=u'%s'% r[1],
name=u'%s' % r[1],
flagDeleted=u'N',
)
xml = etree.tostring(
root,
pretty_print = True,
xml_declaration = True,
encoding='UTF-8',
standalone="yes"
)
with open('xmls/brand.xml', 'w') as f:
f.write(xml)
Отредактировано xammett (Янв. 14, 2017 16:32:00)
Офлайн
Достаточно знать тип элемента набора записей. Его можно описывать отдельно и особо, а можно брать из метаданных БД. Создаём шункцию, получающую тип и шаблон заполнения.
Офлайн
def select_records_to_file(element, expdate, table, subelement_attr_func, outfile): root = etree.Element(element, ExportDate=expdate) data = sql_exec('select * from ' + table) for r in data: etree.SubElement( root, table, **subelement_attr_func(r) ) xml = etree.tostring( root, pretty_print = True, xml_declaration = True, encoding='UTF-8', standalone="yes" ) with open(outfile, 'w') as f: f.write(xml) def make_elem_attrib_city(lst): out = dict(id=str(lst[0]), guid=str(lst[0]), name=u'%s' % lst[2], flagDeleted=u'N', country=str(lst[1]), region=str(lst[3]), isDistrict=u'N') return out def make_elem_attrib_brand(lst): out = dict(id=str(lst[0]), shortName=u'%s'% lst[1], name=u'%s' % lst[1], flagDeleted=u'N') return out select_records_to_file('CityList', '2016-12-05T17:55:55', 'city', make_elem_attrib_city, 'city.xml') select_records_to_file('BrandList', '2016-12-05T17:55:55', 'brand', make_elem_attrib_brand, 'xmls/brand.xml')
Отредактировано py.user.next (Янв. 15, 2017 00:34:39)
Офлайн
py.user.nextСпасибо, попробую)
Офлайн