Ramblings

March 29, 2008

Exporting a web2py table in XML

Filed under: cool, dev, education, one-liner, orm, web2py — michaelangela @ 4:02 am

I recently wrote about exporting a Django database to xml. As a courtesy, Massimo, creator of web2py, put together a great little example for web2py

exporting in XML – web2py Web Framework | Google Groups

def export_xml(rows):
    idx=range(len(rows.colnames))
    colnames=[item.replace('.','_') for item in rows.colnames]
    records=[]
    for row in rows.response: records.append(TAG['record'](*[TAG[colnames[i]](row[i]) for i in idx]))
    return str(TAG['records'](*records))>/pre>

Here is how you would use it:

assuming:
db=SQLDB('sqlite://test.db')
db.define_table('mytable',SQLField('myfield'))
for i in range(100): db.mytable.aaa.insert(myfield=i)




def index():
    response.headers['Content-Type']='application/xml'
    return export_xml(db().select(db.mytable.ALL))

This is using the version currently in trunk. The next update (1.28) should be out in about 1 week though so it should be possible with the release version very soon. One thing I really like about web2py’s tag handling is the TAG item. You can make any tag needed with that and it’s quite sweet.

This particular example just defines the export function, defines a database, a connection, a table, populates the table, and shows how to use it. Sweet. If I get the change, I’ll port a current Django app to web2py… but future apps will be on web2py I think.

And the server is using the wsgi server of cherrypy so it’s rockin’.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: