带有Zeep身份验证的Python SOAP客户端

2024-05-19 18:41:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用Zeep来实现一个SOAP客户端,因为它似乎是目前唯一维护的库:

  • ZSI看起来很不错,但它的最新版本是2006年的pypi
  • 肥皂水似乎是一个受欢迎的替代品,但大师自2011年以来就未被维护,有很多叉子,但似乎没有一个“官方”和“近期”足以用于大型项目。

因此,尝试使用Zeep时,我被服务器访问WSDL所需的身份验证所困扰。

这种操作在ZSI中相当简单:

from ZSI.client import Binding
from ZSI.auth import AUTH

b = Binding(url='http://mysite.dom/services/MyWebServices?WSDL')
b.SetAuth(AUTH.httpbasic, 'userid', 'password')

我可以在Zeep的主目录中找到类似的东西:

from six.moves.urllib.parse import urlparse
from zeep.cache import InMemoryCache, SqliteCache
from zeep.client import Client
from zeep.transports import Transport

cache = SqliteCache() if args.cache else InMemoryCache()
transport_kwargs = {'cache': cache}
result = urlparse(args.wsdl_file)
if result.username or result.password:
    transport_kwargs['http_auth'] = (result.username, result.password)
transport = Transport(**transport_kwargs)
client = Client(args.wsdl_file, transport=transport)

但这在我的情况下不起作用,我得到一个错误:

Exception: HTTPConnectionPool(host='schemas.xmlsoap.org', port=80): Max retries exceeded with url: /soap/encoding/ (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x7f3dab9d30b8>: Failed to establish a new connection: [Errno 110] Connection timed out',))

Tags: fromimportclientauthcacheargspasswordresult
3条回答

对于基本访问身份验证,可以使用requests模块中的HTTPBasicAuth类,如Zeep文档http://docs.python-zeep.org/en/master/transport.html中所述:

from requests.auth import HTTPBasicAuth  # or HTTPDigestAuth, or OAuth1, etc.
from zeep import Client
from zeep.transports import Transport

client = Client('http://my-endpoint.com/production.svc?wsdl',
    transport=Transport(http_auth=HTTPBasicAuth(user, password)))

可能对于较新版本的zeep,较旧的解决方案不再工作。Here is the new way

from requests.auth import HTTPBasicAuth  # or HTTPDigestAuth, or OAuth1, etc.
from requests import Session
from zeep import Client
from zeep.transports import Transport

session = Session()
session.auth = HTTPBasicAuth(user, password)
client = Client('http://my-endpoint.com/production.svc?wsdl',
            transport=Transport(session=session))

在我的例子中,我使用的是必需的WS-Security(WSSE),而不是HTTP。

from zeep import Client
from zeep.wsse.username import UsernameToken

client = Client(<wsdl_url>, wsse=UsernameToken(<username>, <password>)

相关问题 更多 >