【问题标题】:Sending SOAP request using Python Requests使用 Python 请求发送 SOAP 请求
【发布时间】:2013-08-13 02:03:22
【问题描述】:

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

【问题讨论】:

  • 这个解决方案怎么样? stackoverflow.com/q/15569330/2620328
  • 不应该使用肥皂水;
  • @DeepankarBajpeyi 为什么不呢?这是唯一适合这项工作的工具。
  • 您可以将requests.Session 传递给zeep
  • @IanStapletonCordasco 即使在 2013 年 suds 已经死了。

标签: python soap python-requests


【解决方案1】:

确实有可能。

这是一个使用普通请求库调用 Wea​​ther SOAP 服务的示例:

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

一些注意事项:

  • 标题很重要。如果没有正确的标头,大多数 SOAP 请求将无法工作。 application/soap+xml 可能是更 正确 要使用的标头(但气象服务更喜欢 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()

有些人提到了 suds 库。 Suds 可能是与 SOAP 交互更正确的方式,但我经常发现当你的 WDSL 格式不正确时它会有点恐慌(TBH,当你'与仍在使用 SOAP 的机构打交道;))。

您可以像这样使用泡沫来完成上述操作:

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 

注意:使用 suds 时,您几乎总是需要use the doctor

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

sudo tcpdump -As 0 

这有助于检查实际通过网络传输的请求。

以上两个代码sn-ps也可以作为gist获得:

【讨论】:

  • 如果服务请求用户名和密码怎么办?在哪里注明?
  • @toast38coza wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL -->“/WeatherWS”应用程序中的服务器错误。请更新示例。
  • @toast38coza 在上面的请求示例中,我从哪里获得标头和正文变量的信息?
  • 在 fedorahosted.org 上不再提供 Suds 文档。这是a link Wayback Machine 上文档的快照。
  • 无论“使用医生”是什么意思,这个链接现在已经失效了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-25
  • 2012-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-25
相关资源
最近更新 更多