P
P
pcdesign2015-02-21 09:34:53
Flask
pcdesign, 2015-02-21 09:34:53

How to pass select query result from mysql to xml?

@app.route('/getxml')
def getxml():
    g.cur.execute("""select * from table""")
    o = g.cur.fetchall()


The "o" variable contains the result of the select query.
How to turn all this economy into XML?
Advise, plz, a module to do this without manual templates and with little bloodshed.

PS: Python 3.4.1

PS2: And it is desirable to get by with a small number of lines.
1) bash Just one line. 2) perl
mysql --xml -e 'use dbname; SELECT * from tb'

use XML::Dumper;
print new XML::Dumper->pl2xml($o);

Just two lines.
$o is fetchall_arrayref, same as g.cur.fetchall() in Python

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oscar Django, 2015-02-21
@winordie

A bike

def fetchall_xml(cur, pretty_print=True):
    import lxml.etree

    fields_value = cur.fetchall()
    fields_name = tuple(i[0] for i in cur.description)

    elements = lxml.etree.Element('elements')
    for el in fields_value:
        element = lxml.etree.SubElement(elements, 'element', attrib={'foo': 'bar'})
        for j in range(len(fields_name)):
            lxml.etree.SubElement(element, str(fields_name[j])).text = '{}'.format(el[j])
    return lxml.etree.tounicode(elements, pretty_print=pretty_print)


def main():
    conn = sqlite3.connect('compare.db')
    cur = conn.cursor()
    cur.execute('SELECT * FROM PRODUCT_EXCHANGERATE')

    xml = fetchall_xml(cur)
    print(xml)

main()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question