[英]XML POST with Python Requests
I'm trying to use the uClassify API to categorize objects based on a text. 我正在尝试使用uClassify API对基于文本的对象进行分类。 To interact with the API, I need to make XML POST requests, such as:
要与API交互,我需要发出XML POST请求,例如:
<?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. 我尝试使用HTTP Requests模块以及xml.etree.ElementTree来创建XML树,但是我在左右方向上遇到错误。 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
Not a requests
method, but here's a real simple recipe using urllib2
from my codebase: 不是
requests
方法,而是使用我的代码库中的urllib2
简单配方:
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
. 我怀疑您缺少的是使用
tostring
转换您命名为root
的ElementTree
Element
。
一次,当我不得不做类似的事情时,我这样做:
requests.post(url, data=xml_string, headers={'Content-Type':'application/xml; charset=UTF-8'})
It's waiting for a string XML, try something like this (using requests): 它正在等待字符串XML,请尝试如下操作(使用请求):
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.