In this tutorial, I will use the source code which I have made in the last tutorial for the demo.
As you can see in the last tutorial, I print out the string look like json but it’s not json format. Since we used web.py library to build a restful api, the output return must be in json format or jsonp format (What is the different between json and jsonp ? you can read it here)
How can I make the python return json or jsonp after reading data from xml file or from database
In the
class list_users
I change the old code with this code below
class list_users: def GET(self): data = {} i = 0 for child in root: print child.tag, child.attrib data[i] = child.attrib i=i+1 callback_name = web.input(callback='callback').callback web.header('Content-Type', 'application/json') return json.dumps(data)
The idea in this code is I used a array call
data
to store the values which I get from xml file. And then, I use
json
library to dump the data into json format
So the full source code will look like
#!/usr/bin/env python import web import json import xml.etree.ElementTree as ET tree = ET.parse('user_data.xml') root = tree.getroot() urls = ( '/users', 'list_users', '/users/(.*)', 'get_user' ) app = web.application(urls, globals()) class list_users: def GET(self): data = {} i = 0 for child in root: print child.tag, child.attrib data[i] = child.attrib i=i+1 callback_name = web.input(callback='callback').callback web.header('Content-Type', 'application/json') return json.dumps(data) class get_user: def GET(self, user): for child in root: if child.attrib['id'] == user: return str(child.attrib) if __name__ == "__main__": app.run()
And if you want to return the jsonp for some off cross-domain purpose, you can replace the return with
return '%s(%s)' % (callback_name, json.dumps(data))