使用Python请求发送SOAP请求

Dee*_*eyi 63 python soap python-requests

是否可以使用Python的requests库发送SOAP请求?

toa*_*oza 131

这确实是可能的.

以下是使用普通请求lib调用Weather SOAP Service的示例:

import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
         <SOAP-ENV:Envelope xmlns:ns0="http://ws.cdyne.com/WeatherWS/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" 
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
            <SOAP-ENV:Header/>
              <ns1:Body><ns0:GetWeatherInformation/></ns1:Body>
         </SOAP-ENV:Envelope>"""

response = requests.post(url,data=body,headers=headers)
print response.content
Run Code Online (Sandbox Code Playgroud)

一些说明:

  • 标题很重要.没有正确的标头,大多数SOAP请求都无法工作.application/soap+xml可能是更正确的标题使用(但是weatherservice更喜欢text/xml
  • 这将以xml字符串的形式返回响应 - 然后您需要解析该xml.
  • 为简单起见,我将请求作为纯文本包含在内.但最佳做法是将其存储为模板,然后您可以使用jinja2(例如)加载它 - 并传入变量.

例如:

from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()
Run Code Online (Sandbox Code Playgroud)

有人提到了肥皂库.Suds可能是与SOAP交互的更正确的方式,但我经常发现当你的WDSL形成不良时会有一点恐慌(TBH,当你处理一个仍然存在的机构时,TBH很可能不会使用SOAP;)).

您可以使用suds这样做:

from suds.client import Client
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
client = Client(url)
print client ## shows the details of this service

result = client.service.GetWeatherInformation() 
print result 
Run Code Online (Sandbox Code Playgroud)

注意:使用肥皂水时,你几乎总是需要使用医生!

最后,调试SOAP有一点好处; TCPdump是你的朋友.在Mac上,您可以像这样运行TCPdump:

sudo tcpdump -As 0 
Run Code Online (Sandbox Code Playgroud)

这有助于检查实际通过电线的请求.

以上两个代码段也可作为要点:

  • @toast38coza http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL - >'/ WeatherWS'应用程序中的服务器错误.请更新示例. (3认同)
  • 如果服务请求用户名和密码怎么办?在哪里注意它们? (2认同)