Reputation: 382
I'm trying to use the uClassify API to categorize objects based on a text. To interact with the API, I need to make XML POST requests, such as:
<?xml version="1.0" encoding="utf-8" ?>
<uclassify xmlns="http://api.uclassify.com/1/RequestSchema" version="1.01">
<writeCalls writeApiKey="YOUR_WRITE_API_KEY_HERE" classifierName="ManOrWoman">
<create id="CreateManOrWoman"/>
</writeCalls>
</uclassify>
I tried to do this using the HTTP Requests module as well as xml.etree.ElementTree to create an XML tree, but I am getting errors left and right. Here's some code I tried:
>>> import elementtree.ElementTree as ET
>>> from xml.etree.cElementTree import Element, ElementTree
>>> import requests
>>>
>>> root = ET.Element("uclassify", xlms="http://api.uclassify.com/1/RequestSchema", version="1.01")
>>> head = ET.SubElement(root, "writeCalls", writeApiKey="*************", classifierName="test")
>>> action = ET.SubElement(head, "create", id="CreateTest")
>>> tree = ElementTree(root)
>>>
>>> r = requests.post('http://api.uclassify.com/', tree)
>>>
>>> ........
>>> TypeError: must be convertible to a buffer, not ElementTree
Upvotes: 4
Views: 19834
Reputation: 626
Once, when I had to do a similar thing, I did like this:
requests.post(url, data=xml_string, headers={'Content-Type':'application/xml; charset=UTF-8'})
Upvotes: 5
Reputation: 1339
It's waiting for a string XML, try something like this (using requests):
input_string_xml = ElementTree.tostring(tree, encoding='utf8', method='xml')
param_data = {'xml': input_xml}
output_xml = requests.post("http://api.uclassify.com/", data=param_data)
Upvotes: 1
Reputation: 21269
Not a requests
method, but here's a real simple recipe using urllib2
from my codebase:
import urllib2
from elementtree import ElementTree
def post(url, data, contenttype):
request = urllib2.Request(url, data)
request.add_header('Content-Type', contenttype)
response = urllib2.urlopen(request)
return response.read()
def postxml(url, elem):
data = ElementTree.tostring(elem, encoding='UTF-8')
return post(url, data, 'text/xml')
I suspect what you're missing is the use of tostring
to convert the ElementTree
Element
that you named root
.
Upvotes: 4