Introduction to the SOAP project in Python and Its Application in web development, pythonsoap

Source: Internet
Author: User
Tags soap client

Introduction to the SOAP project in Python and Its Application in web development, pythonsoap

SOAP. py client and server

SOAP. py contains some basic things. There is no Web Service Description Language (WSDL) or anything else, only transparent support for SOAP clients and servers implemented using Python. Even a good feature in this package is only related to the infrastructure: SOAP. py supports Secure Socket Layer (SSL) for encrypted SOAP transmission. To use this function, you must install M2Crypto. M2Crypto is a library that contains various encryption tools and formats, from RSA and DSA to HTTPs and S/MIME. In this section, we are not going to discuss SSL support for SOAP. py.
SOAP operation Abstract

So far, SOAP utilities are still popular open source code activities using Python. The following is the outline of the project and their current status. First, participants:

  • 4 Suite SOAP, managed by Fourthought
  • SOAPy, managed by Adam Elman
  • SOAP. py, a Web Service Project of the Python Project
  • Soaplib, managed by Secret Labs
  • Orchard, managed by Ken MacLeod
  • PySOAP, managed by Dave Warner

4. Suite SOAP is our own implementation. We have used it in the first three sections of this column (see references for links ). It is still under development.

SOAPy was announced in April 2001 and is currently in alpha preparation, but it seems that development has stopped.

SOAP. py development is frozen. The SOAP. py project is sponsored by actzero, but actzero is no longer engaged in this industry. Invite organizations that voluntarily develop/maintain SOAP. py.

Soaplib development seems to have slowed down. Considering the large amount of work undertaken by Secret Labs during this period, we may be able to understand why this is the case. The Swedish company is headed by Fredrik Lundh. He is a famous "workaholic" in the Python circle and a member of the board of directors of Python Association. Secret Labs also developed PythonWare (a core and important additional module of Python); PythonWorks (a leading Python IDE ); python Imaging Library and many other good things (daily Python-URL Web logs are part of them ).

Orchard is a data management framework. It is basically a method to manage different data formats using a public interface. It implements a SOAP client as a basic method (known as a node) to send Orchard data items to the SOAP server in a Remote Procedure Call ).

The PySOAP project is primarily intended to be part of Dave Warner's Church management suite, but it has never released any files, as if it were a lifeless project.

Install

Download the distribution package first (SOAPpy 0.9.7 is the latest distribution package when writing this article), unpack the file, go to the result directory, and SOAP the file. copy py to your preferred location. Of course, this "tendency" is where skills are needed. Many of these SOAP lib libraries use different "soap. py" combinations of upper and lower cases as the module names, so be careful. Of course, UNIX users only need to care about whether the case is exactly matched, but for Windows users, even the conflict between "SOAP. py" and "soap. py" may cause trouble. Orchard's SOAP. py also has a name that is prone to conflicts, but it may avoid all problems because its modules are cleverly placed in the Orchard package.

In short, we recommend that you use a unique package name when installing all Python SOAP modules. In our case, we found a suitable directory in PYTHONPATH, created a WebServices package, and put SOAP. py in this package. Therefore, in Linux:

$ mkdir ~/lib/python/WebServices$ touch ~/lib/python/WebServices/__init__.py$ cp SOAPpy097/SOAP.py ~/lib/python/WebServices


Note that the second important command will generate a _ init _. py file, which marks the WebServices directory as a Python package. If you need to package the code into a Windows version, you may want to enter some comments to the empty file because some Windows tools do not create empty files.

You have gone deep into the topic

For publicly available SOAP servers, there are already registration centers for several activities. The most popular one is XMethods. Of course, it is also a very interesting guide, through which we can understand the actual situation of SOAP, rather than let it boast. Most of the public Web services here are still irrelevant, and it is hardly worth mentioning that the new model is brave, but it is another thing. In fact, we will select a public service to demonstrate and test how to use SOAP. py as a SOAP client.

Or, we can try. The first service tried by the author, the health care provider locator, shows a trap in the current state of SOAP interoperability in the case of the following error messages:

WebServices.SOAP.faultType: <Fault soap:Client: Server did not recognize the value ofHTTP Header SOAPAction: "".>


Oh. SOAPAction is an HTTP header used to mark the accessed service. It is a required header in a SOAP request, but even after the required header is set (only a pair of null double quotes), the above error still exists. The author found that this problem exists in most ms soap implementations. After trying these services, we concluded that Delphi implementation seems to be similar to SOAP. py works best, but it returns complex types, such as list and SOAP, even if it is implemented using Delphi. py cannot use them, and WebServices without data are returned. SOAP. typedArrayType.

Finally, the author chooses a quite suitable Web service, which returns the abusive language frequently used by Captain Haddock, a character in the cartoon "Adventures of Ding ding" (yes, most Web services use this ). Listing 1 (curse. py) is the program.

Listing 1: accessing the SOAP. py program of the Curse generator SOAP Service

 #!/usr/bin/env python#http://xmethods.net/detail.html?id=175import sys#Import the SOAP.py machineryfrom WebServices import SOAPremote = SOAP.SOAPProxy("http://www.tankebolaget.se/scripts/Haddock.exe/soap/IHaddock", namespace="urn:HaddockIntf-IHaddock", soapaction="urn:HaddockIntf-IHaddock#Curse")try: lang = sys.argv[1]except IndexError: lang = "us"result = remote.Curse(LangCode=lang)print "What captain Haddock had to say: "%s""%result


Integrate everything

After importing data to the database, we will set the proxy Object remote. This object converts a method call to a remote SOAP message. Its initializer uses key parameters for managing remote requests: the server URI (called the "endpoint") and the XML namespace of the request element (through it, SOAP-as-RPC converts the verbal commitment to the XML base) and the SOAPAction header value.

Next, we will determine the method parameters. For this Web service, the method parameters are only the language of Haddock, Swedish ("se") or English (Strangely, is "us" rather than "en ").

Finally, we call the method with the correct name. The Curse of the proxy object performs the SOAP call and then prints the result. The following session demonstrates the use of this program:

$ python curse.pyWhat captain Haddock had to say: "Ectoplasmic Byproduct!"


Our own SOAP server

It is quite easy to use SOAP. py to implement a SOAP server. As an example, we will create a field and implement a common service: a program that provides the year and month, which prints the calendar in the form of a string. Its program server is listing 2 (calendar-ws.py ).

List 2: implement the SOAP. py program of the Calendar Server

 #!/usr/bin/env pythonimport sys, calendar#Import the SOAP.py machineryfrom WebServices import SOAPCAL_NS = "http://uche.ogbuji.net/eg/ws/simple-cal"class Calendar: def getMonth(self, year, month):  return calendar.month(year, month) def getYear(self, year):  return calendar.calendar(year)server = SOAP.SOAPServer(("localhost", 8888))cal = Calendar()server.registerObject(cal, CAL_NS)print "Starting server..."server.serve_forever()


After necessary import, we define the expected namespace (CAL_NS) of the soap request element for our server ). Next, we define classes that implement all methods. These methods will be exposed as SOAP methods. You can also register a single function as a SOAP method, but the class method is the most flexible, especially when you want to manage the status between calls. This Calendar class defines a method of getMonth, which uses the Python built-in Calendar module to return the monthly Calendar in a text form, and defines another method to return the Calendar of the entire year.

Then, create an instance of the SOAP server framework, which also carries the command for listening to port 8888. We must also create an instance of the Calendar class. This instance is registered in the next line to process SOAP messages and specify the relevant namespace for it. Finally, we call the serve_forever method. This method is not returned until the process is terminated.

To run the server, open another command shell and execute the python calendar-ws.py. Run ctrl-C to kill the process.

We can use a client that is also written in SOAP. py to test the server, but that is too obvious. We still use low-level Python to write the client to construct the SOAP response as an XML string and send an HTTP message. This program (testcal. py) is in listing 3.

Listing 3: clients accessing the calendar service written in the Python core library

 import sys, httplibSERVER_ADDR = "127.0.0.1"SERVER_PORT = 8888CAL_NS = "http://uche.ogbuji.net/ws/eg/simple-cal"BODY_TEMPLATE = """<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:s="http://uche.ogbuji.net/eg/ws/simple-cal" xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xmlns:xsd="http://www.w3.org/1999/XMLSchema" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <SOAP-ENV:Body>  <s:getMonth>   <year xsi:type="xsd:integer">%s</year>   <month xsi:type="xsd:integer">%s</month>  </s:getMonth> </SOAP-ENV:Body></SOAP-ENV:Envelope>"""def GetMonth():  year = 2001  month = 12  body = BODY_TEMPLATE%(year, month)  blen = len(body)  requestor = httplib.HTTP(SERVER_ADDR, SERVER_PORT)  requestor.putrequest("POST", "cal-server")  requestor.putheader("Host", SERVER_ADDR)  requestor.putheader("Content-Type", "text/plain; charset="utf-8"")  requestor.putheader("Content  reply_body = requestor.getfi-Length", str(blen))  requestor.putheader("SOAPAction", "http://uche.ogbuji.net/eg/ws/simple-car")  requestor.endheaders()  requestor.send(body)  (status_code, message, reply_headers) = requestor.getreply()le().read()  print "status code:", status_code  print "status message:", message  print "HTTP reply body:\n", reply_bodyif __name__ == "__main__":  GetMonth()


The following session demonstrates the running status of this test.

$ python testcal.pystatus code: 200status message: OKHTTP reply body:<?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"xmlns:xsd="http://www.w3.org/1999/XMLSchema" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"><SOAP-ENV:Body><getMonthResponse SOAP-ENC:root="1"><Result xsi:type="xsd:string">  December 2001Mo Tu We Th Fr Sa Su        1 2 3 4 5 6 7 8 910 11 12 13 14 15 1617 18 19 20 21 22 2324 25 26 27 28 29 3031</Result></getMonthResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>


Bytes carefully reviewed

If you find the row self. debug = 0 and change "0" to "1" (This is SOAP. line 210th in py version 0.9.7), one thing to note is that you can obtain detailed information about the actual SOAP message to be exchanged and other key data for debugging and tracking, this is useful to you. As an example, a session is provided below, which is a session of the previous curses. py program that turned on the debug information display switch:

$ python curse.py *** Outgoing HTTP headers **********************************************POST /scripts/Haddock.exe/soap/IHaddock HTTP/1.0Host: www.tankebolaget.seUser-agent: SOAP.py 0.9.7 (actzero.com)Content-type: text/xml; charset="UTF-8"Content-length: 523SOAPAction: "urn:HaddockIntf-IHaddock#Curse"*************************************************************************** Outgoing SOAP ******************************************************<?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/1999/XMLSchema" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"><SOAP-ENV:Body><ns1:Curse xmlns:ns1="urn:HaddockIntf-IHaddock" SOAP-ENC:root="1"><LangCode xsi:type="xsd:string">us</LangCode></ns1:Curse></SOAP-ENV:Body></SOAP-ENV:Envelope>*************************************************************************** Incoming HTTP headers **********************************************HTTP/1.? 200 OKServer: Microsoft-IIS/5.0Date: Tue, 11 Sep 2001 16:40:19 GMTContent-Type: text/xmlContent-Length: 528Content:*************************************************************************** Incoming SOAP ******************************************************<?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/1999/XMLSchema" xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"><SOAP-ENV:Body><NS1:CurseResponse xmlns:NS1="urn:HaddockIntf-IHaddock" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><NS1:return xsi:type="xsd:string">Anacoluthons!</NS1:return></NS1:CurseResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>************************************************************************What captain Haddock had to say: "Anacoluthons!"


For comparison, you can obtain the same information in the old Python script or program with the following code:

import calendarreturn calendar.month(2001, 10)


SOAP. py Summary

We have noticed that although there are still some problems with SOAP. py interoperability, available debugging tools are expected to help.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.