Nice programing

Python 요청을 사용하여 SOAP 요청 보내기

nicepro 2020. 11. 30. 19:52
반응형

Python 요청을 사용하여 SOAP 요청 보내기


Python의 requests라이브러리 를 사용 하여 SOAP 요청을 보낼 수 있습니까?


실제로 가능합니다.

다음은 일반 요청 lib를 사용하여 날씨 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정확한 헤더 일 것입니다 (그러나 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()

어떤 사람들은 비눗물 라이브러리를 언급했습니다. 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 

참고 : 비눗물을 사용할 때 거의 항상 의사사용해야합니다 !

마지막으로 SOAP 디버깅에 대한 약간의 보너스입니다. TCPdump는 당신의 친구입니다. Mac에서는 다음과 같이 TCPdump를 실행할 수 있습니다.

sudo tcpdump -As 0 

이는 실제로 전송되는 요청을 검사하는 데 유용 할 수 있습니다.

위의 두 코드 스 니펫은 요점으로도 사용할 수 있습니다.

참고 URL : https://stackoverflow.com/questions/18175489/sending-soap-request-using-python-requests

반응형