Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to POST an xml element in python

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!

like image 342
G Ullman Avatar asked Jun 24 '10 00:06

G Ullman


People also ask

How do I post an XML request?

To post XML data to the server, you need to make an HTTP POST request, include the XML in the body of the request message, and set the correct MIME type for the XML. The correct MIME type for XML is application/xml.


2 Answers

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)
like image 115
Matthew Flaschen Avatar answered Oct 20 '22 12:10

Matthew Flaschen


Here is a full example (snippet) for sending post data (xml) to an URL:

def execQualysAction(username,password,url,request_data):
  import urllib,urrlib2
  xml_output = None 
  try:
    base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')  
    headers = {'X-Requested-With' : 'urllib2','Content-Type': 'application/xml','Authorization': 'Basic %s' % base64string}
    req = urllib2.Request(url=url,data=request_data,headers=headers)
    response = urllib2.urlopen(req,timeout=int(TIMEOUT))
    xml_output = response.read()
    if args.verbose>1:
      print "Result of executing action request",request_data,"is:",xml_output
  except:
    xml_output = '<RESULT></RESULT>'
    traceback.print_exc(file=sys.stdout)
    print '-'*60

finally:

return xml_output
like image 33
Vladimir Jirasek Avatar answered Oct 20 '22 11:10

Vladimir Jirasek