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
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'})
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With