consume xml from RestFul webservices


/ Published in: Python
Save to your folder(s)

ElementTree is provided as part of the standard Python libs. ElementTree is pure python, and cElementTree is the faster C implementation:

Here's an example usage, where I'm consuming xml from a RESTful web service:


Copy this code and paste it in your HTML
  1. # Try to use the C implementation first, falling back to python
  2. try:
  3. from xml.etree import cElementTree as ElementTree
  4. except ImportError, e:
  5. from xml.etree import ElementTree
  6.  
  7. ##########
  8.  
  9. def find(*args, **kwargs):
  10. """Find a book in the collection specified"""
  11.  
  12. search_args = [('access_key', api_key),]
  13. if not is_valid_collection(kwargs['collection']):
  14. return None
  15. kwargs.pop('collection')
  16. for key in kwargs:
  17. # Only the first keword is honored
  18. if kwargs[key]:
  19. search_args.append(('index1', key))
  20. search_args.append(('value1', kwargs[key]))
  21. break
  22.  
  23. url = urllib.basejoin(api_url, '%s.xml' % 'books')
  24. data = urllib.urlencode(search_args)
  25. req = urllib2.urlopen(url, data)
  26. rdata = []
  27. chunk = 'xx'
  28. while chunk:
  29. chunk = req.read()
  30. if chunk:
  31. rdata.append(chunk)
  32. tree = ElementTree.fromstring(''.join(rdata))
  33. results = []
  34. for i, elem in enumerate(tree.getiterator('BookData')):
  35. results.append(
  36. {'isbn': elem.get('isbn'),
  37. 'isbn13': elem.get('isbn13'),
  38. 'title': elem.find('Title').text,
  39. 'author': elem.find('AuthorsText').text,
  40. 'publisher': elem.find('PublisherText').text,}
  41. )
  42. return results

URL: http://stackoverflow.com/questions/804992/how-to-consume-xml-from-restful-web-services-using-django-python

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.