2010-06-24 48 views
12

基本上我有這個xml元素(xml.etree.ElementTree),我想將它發佈到一個url。目前我正在做這樣的事情如何在python中發佈xml元素

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

我敢肯定,作品和所有的,但不知道是否有一些更好的做法或方法來做到這一點,而不首先將其轉換爲一個字符串。

謝謝!

+0

使用Python [發佈XML文件的可能的複製](https://stackoverflow.com/questions/16192638/post-xml-file-using-python) – 2017-10-17 13:35:49

回答

16

如果這是您自己的API,我會考慮POST爲application/xml。默認值爲application/x-www-form-urlencoded,這是爲HTML表單數據而非單個XML文檔。

req = urllib2.Request(url=url, 
         data=xml_string, 
         headers={'Content-Type': 'application/xml'}) 
urllib2.urlopen(req) 
+0

請注意,您不必構建開門紅。你可以簡單地調用'urllib2.urlopen(req)' - urlopen可以接受Request對象以及普通的URL字符串。 – 2010-06-24 00:51:15

+0

謝謝,@Walter。 – 2010-06-24 00:57:29

0

不,我認爲這可能是最好的方式 - 它很簡單,你還能要求什麼?很明顯,XML必須在某個時刻轉換爲字符串,除非您使用內置支持的XML庫來發布到URL(不是xml.etree),您必須自己動手。

1

這裏是POST數據(XML)發送到一個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 

最後:

return xml_output 
+0

請改善你的格式。 – pinckerman 2013-09-25 20:56:22