Найти - Пользователи
Полная версия: как Несколько однотипных xml скриптов превратить в один класс ?
Начало » Python для новичков » как Несколько однотипных xml скриптов превратить в один класс ?
1
xammett
Всем привет,
есть несколько файлов с похожим кодом,
отличаются только названиями полей м значениями в 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)
py.user.next
  
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')
xammett
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',
py.user.next
Ну, приведи несколько файлов, а то непонятно, что ты хочешь, то одно пишешь, то другое.

xammett
Самая суть, что в каждом таком файле названия полей и строки из базы разные.

xammett
абстрактно передавать название колонки и поле из базы

Можно сделать замыкание - не вопрос, но ты же опять скажешь, что тебе надо не это.
xammett
py.user.next
Ну, приведи несколько файлов, а то непонятно, что ты хочешь, то одно пишешь, то другое.

Как сформировать 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)

Второй
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)
Shaman
Достаточно знать тип элемента набора записей. Его можно описывать отдельно и особо, а можно брать из метаданных БД. Создаём шункцию, получающую тип и шаблон заполнения.
py.user.next
  
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')
xammett
py.user.next
Спасибо, попробую)
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB