views:

39

answers:

2

Basically I have this xml element (xml.etree.ElementTree) and I want to POST it to a url. Currently I'm doing something like

xml_string = xml.etree.ElementTree.tostring(my_element)
data = urllib.urlencode({'xml': xml_string})
response = urllib2.urlopen(url, data)

I'm pretty sure that works and all, but was wondering if there is some better practice or way to do it without converting it to a string first.

Thanks!

A: 

No, I think that's probably the best way to do it - it's short and simple, what more could you ask for? Obviously the XML has to be converted to a string at some point, and unless you're using an XML library with builtin support for POSTing to a URL (which xml.etree is not), you'll have to do it yourself.

David Zaslavsky
+2  A: 

If this is your own API, I would consider POSTing as application/xml. The default is application/x-www-form-urlencoded, which is meant for HTML form data, not a single XML document.

req = urllib2.Request(url=url, 
                      data=xml_string, 
                      headers={'Content-Type': 'application/xml'})
urllib2.urlopen(req)
Matthew Flaschen
Note that you don't have to build the opener. You can simply call `urllib2.urlopen(req)` -- urlopen can take Request objects as well as plain URL strings.
Walter Mundt
Thanks, @Walter.
Matthew Flaschen