Python에서 WSDL (SOAP) 웹 서비스를 사용하려면 어떻게해야합니까?
Python에서 WSDL SOAP 기반 웹 서비스를 사용하고 싶습니다. Dive Into Python 코드를 살펴 봤지만 SOAPpy 모듈은 Python 2.5에서 작동하지 않습니다.
부분적으로 작동하지만 특정 유형 (suds.TypeNotFound : 유형을 찾을 수 없음 : 'item')으로 나누는 suds 를 사용해 보았습니다 .
또한 클라이언트를 보았지만 WSDL을 지원하지 않는 것 같습니다.
그리고 ZSI를 살펴 봤지만 매우 복잡해 보입니다. 누구든지 샘플 코드가 있습니까?
WSDL은 https://ws.pingdom.com/soap/PingdomAPI.wsdl 이며 PHP 5 SOAP 클라이언트와 잘 작동합니다.
SUDS를 살펴 보는 것이 좋습니다.
"Suds는 웹 서비스 소비를위한 경량 SOAP 파이썬 클라이언트입니다."
매우 유망하며 아직 문서화가 잘되어 있지는 않지만 비교적 깨끗하고 파이썬으로 보이는 비교적 새로운 라이브러리가 있습니다 : python zeep .
예를 보려면 이 답변 을 참조하십시오 .
최근에 같은 문제가 발생했습니다. 내 솔루션의 개요는 다음과 같습니다.
필요한 기본 구성 코드 블록
다음은 클라이언트 애플리케이션의 필수 기본 코드 블록입니다.
- 세션 요청 섹션 : 제공자와의 세션 요청
- 세션 인증 섹션 : 공급자에게 자격 증명 제공
- 클라이언트 섹션 : 클라이언트 생성
- 보안 헤더 섹션 : 클라이언트에 WS-Security 헤더 추가
- 소비 섹션 : 필요에 따라 사용 가능한 작업 (또는 방법) 소비
어떤 모듈이 필요합니까?
많은 사람들이 urllib2와 같은 파이썬 모듈을 사용하도록 제안했습니다. 그러나 적어도이 특정 프로젝트에는 모듈이 작동하지 않습니다.
다음은 필요한 모듈 목록입니다. 우선, 다음 링크에서 최신 버전의 sud를 다운로드하여 설치해야합니다.
pypi.python.org/pypi/suds-jurko/0.4.1.jurko.2
또한 다음 링크에서 요청 및 suds_requests 모듈을 각각 다운로드하여 설치해야합니다 (면책 조항 : 여기에 게시 할 수 없으므로 현재 둘 이상의 링크를 게시 할 수 없습니다).
pypi.python.org/pypi/requests
pypi.python.org/pypi/suds_requests/0.1
이러한 모듈을 성공적으로 다운로드하여 설치하면 계속 진행할 수 있습니다.
코드
앞에서 설명한 단계에 따라 코드는 다음과 같습니다. 가져 오기 :
import logging
from suds.client import Client
from suds.wsse import *
from datetime import timedelta,date,datetime,tzinfo
import requests
from requests.auth import HTTPBasicAuth
import suds_requests
세션 요청 및 인증 :
username=input('Username:')
password=input('password:')
session = requests.session()
session.auth=(username, password)
클라이언트를 작성하십시오.
client = Client(WSDL_URL, faults=False, cachingpolicy=1, location=WSDL_URL, transport=suds_requests.RequestsTransport(session))
WS-Security 헤더 추가 :
...
addSecurityHeader(client,username,password)
....
def addSecurityHeader(client,username,password):
security=Security()
userNameToken=UsernameToken(username,password)
timeStampToken=Timestamp(validity=600)
security.tokens.append(userNameToken)
security.tokens.append(timeStampToken)
client.set_options(wsse=security)
Please note that this method creates the security header depicted in Fig.1. So, your implementation may vary depending on the correct security header format provided by the owner of the service you are consuming.
Consume the relevant method (or operation) :
result=client.service.methodName(Inputs)
Logging:
One of the best practices in such implementations as this one is logging to see how the communication is executed. In case there is some issue, it makes debugging easy. The following code does basic logging. However, you can log many aspects of the communication in addition to the ones depicted in the code.
logging.basicConfig(level=logging.INFO)
logging.getLogger('suds.client').setLevel(logging.DEBUG)
logging.getLogger('suds.transport').setLevel(logging.DEBUG)
Result:
Here is the result in my case. Note that the server returned HTTP 200. This is the standard success code for HTTP request-response.
(200, (collectionNodeLmp){
timestamp = 2014-12-03 00:00:00-05:00
nodeLmp[] =
(nodeLmp){
pnodeId = 35010357
name = "YADKIN"
mccValue = -0.19
mlcValue = -0.13
price = 36.46
type = "500 KV"
timestamp = 2014-12-03 01:00:00-05:00
errorCodeId = 0
},
(nodeLmp){
pnodeId = 33138769
name = "ZION 1"
mccValue = -0.18
mlcValue = -1.86
price = 34.75
type = "Aggregate"
timestamp = 2014-12-03 01:00:00-05:00
errorCodeId = 0
},
})
Right now (as of 2008), all the SOAP libraries available for Python suck. I recommend avoiding SOAP if possible. The last time we where forced to use a SOAP web service from Python, we wrote a wrapper in C# that handled the SOAP on one side and spoke COM out the other.
I periodically search for a satisfactory answer to this, but no luck so far. I use soapUI + requests + manual labour.
I gave up and used Java the last time I needed to do this, and simply gave up a few times the last time I wanted to do this, but it wasn't essential.
Having successfully used the requests library last year with Project Place's RESTful API, it occurred to me that maybe I could just hand-roll the SOAP requests I want to send in a similar way.
Turns out that's not too difficult, but it is time consuming and prone to error, especially if fields are inconsistently named (the one I'm currently working on today has 'jobId', JobId' and 'JobID'. I use soapUI to load the WSDL to make it easier to extract endpoints etc and perform some manual testing. So far I've been lucky not to have been affected by changes to any WSDL that I'm using.
Zeep is a decent SOAP library for Python that matches what you're asking for: http://docs.python-zeep.org
It's not true SOAPpy does not work with Python 2.5 - it works, although it's very simple and really, really basic. If you want to talk to any more complicated webservice, ZSI is your only friend.
The really useful demo I found is at http://www.ebi.ac.uk/Tools/webservices/tutorials/python - this really helped me to understand how ZSI works.
If you're rolling your own I'd highly recommend looking at http://effbot.org/zone/element-soap.htm.
SOAPpy is now obsolete, AFAIK, replaced by ZSL. It's a moot point, because I can't get either one to work, much less compile, on either Python 2.5 or Python 2.6
#!/usr/bin/python
# -*- coding: utf-8 -*-
# consume_wsdl_soap_ws_pss.py
import logging.config
from pysimplesoap.client import SoapClient
logging.config.dictConfig({
'version': 1,
'formatters': {
'verbose': {
'format': '%(name)s: %(message)s'
}
},
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'verbose',
},
},
'loggers': {
'pysimplesoap.helpers': {
'level': 'DEBUG',
'propagate': True,
'handlers': ['console'],
},
}
})
WSDL_URL = 'http://www.webservicex.net/stockquote.asmx?WSDL'
client = SoapClient(wsdl=WSDL_URL, ns="web", trace=True)
client['AuthHeaderElement'] = {'username': 'someone', 'password': 'nottelling'}
#Discover operations
list_of_services = [service for service in client.services]
print(list_of_services)
#Discover params
method = client.services['StockQuote']
response = client.GetQuote(symbol='GOOG')
print('GetQuote: {}'.format(response['GetQuoteResult']))
참고URL : https://stackoverflow.com/questions/115316/how-can-i-consume-a-wsdl-soap-web-service-in-python
'Programming' 카테고리의 다른 글
ASP.NET MVC 응용 프로그램을 지역화하는 방법은 무엇입니까? (0) | 2020.07.14 |
---|---|
size_t와 std :: size_t의 차이점 (0) | 2020.07.14 |
FIND_IN_SET () 대 IN () (0) | 2020.07.14 |
명령 프롬프트에서 응용 프로그램을“관리자 권한으로 실행”하는 방법은 무엇입니까? (0) | 2020.07.14 |
REST API 토큰 기반 인증 (0) | 2020.07.14 |