是否可以使用 Python 的 requests 库发送 SOAP 请求?
Is it possible to use Python's requests library to send a SOAP request?
推荐答案确实有可能.
以下是使用普通请求库调用 Weather SOAP 服务的示例:
Here is an example calling the Weather SOAP Service using plain requests lib:
import requests url="wsf.cdyne/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="ws.cdyne/WeatherWS/" xmlns:ns1="schemas.xmlsoap/soap/envelope/" xmlns:xsi="www.w3/2001/XMLSchema-instance" xmlns:SOAP-ENV="schemas.xmlsoap/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 可能是更正确 使用的标头(但是weatherservice 更喜欢text/xml
- 这会将响应作为 xml 字符串返回 - 然后您需要解析该 xml.
- 为简单起见,我将请求包含为纯文本.但最佳实践是将其存储为模板,然后您可以使用 jinja2(例如)加载它 - 并传入变量.
- The headers are important. Most SOAP requests will not work without the correct headers. application/soap+xml is probably the more correct header to use (but the weatherservice prefers text/xml
- This will return the response as a string of xml - you would then need to parse that xml.
- For simplicity I have included the request as plain text. But best practise would be to store this as a template, then you can load it using jinja2 (for example) - and also pass in variables.
例如:
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 的机构打交道 ;) ).
Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ).
你可以像这样用肥皂水做上面的事情:
from suds.client import Client url="wsf.cdyne/WeatherWS/Weather.asmx?WSDL" client = Client(url) print client ## shows the details of this service result = client.service.GetWeatherInformation() print result注意:在使用 suds 时,您几乎总是需要看医生!
Note: when using suds, you will almost always end up needing to use the doctor!
最后,调试 SOAP 的一点小收获;TCPdump 是您的朋友.在 Mac 上,你可以像这样运行 TCPdump:
Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so:
sudo tcpdump -As 0这有助于检查实际通过线路的请求.
This can be helpful for inspecting the requests that actually go over the wire.
以上两个代码片段也可作为要点使用:
- 带有请求的 SOAP 请求
- 带有 suds 的 SOAP 请求
更多推荐
使用 Python 请求发送 SOAP 请求
发布评论