miercuri, 5 august 2009

Python invoking web services

Recently, I had to invoke a webservice method from python. One solution found was to build a SOAP request. After the request is built, I use httplib for sending request and receiving an answer from the webservice. For this demo, I'll use www.infovalutar.ro webservice(an exchange rate service from Romania).

------------------------------------------------------------------------------------------------
import httplib

HOST = "www.infovalutar.ro"
URL = "/curs.asmx"

def SOAP_GetMoneda(strMoneda):
strReq = """<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
<getlatestvalue xmlns="http://www.infovalutar.ro/">
<Moneda>%s</Moneda>
</getlatestvalue>
</soap12:Body>
</soap12:Envelope>"""

return strReq % strMoneda

if __name__ == "__main__":
data = SOAP_GetMoneda("USD")

dctHeaders = {"Host" : HOST,
"Content-Type" : "text/xml; charset=utf-8",
"Content-Length" : len(data),
"SOAPAction" : "http://www.infovalutar.ro/getlatestvalue"}

con = httplib.HTTPConnection(HOST)

con.request("POST", URL, data, dctHeaders)
resp = con.getresponse()
print(resp.read())

con.close()
--------------------------------------------------------------------------------

What I don't show in this answer is how to parse the response. This should be a simple fact regarding the fact that soap response is a xml document. In the above presented code, I just print the response on the standard output.

Niciun comentariu:

Trimiteți un comentariu