杰瑞科技汇

Python soaplib如何解析wsdl文件?

Of course! Let's dive into using soaplib to create a web service from a WSDL in Python.

Python soaplib如何解析wsdl文件?-图1
(图片来源网络,侵删)

soaplib is a powerful library for building SOAP (Simple Object Access Protocol) web services. It's particularly known for its ability to generate a WSDL file from your Python code, but it can also be used to create a service that adheres to an existing WSDL.

However, it's important to note that soaplib is no longer actively maintained. The last release was in 2025. For new projects, you should strongly consider using more modern and maintained libraries like zeep (for clients) or spyne (for servers).

This guide will cover:

  1. The soaplib Approach: Creating a service and generating its WSDL.
  2. The Modern Alternative (spyne): How to create a service and generate its WSDL, which is the recommended path today.
  3. Consuming a WSDL with zeep: The standard way to create a client for an existing SOAP service.

The soaplib Approach (Legacy)

The typical soaplib workflow is to define your service logic in Python, and then soaplib automatically generates the WSDL that clients can use to interact with it.

Python soaplib如何解析wsdl文件?-图2
(图片来源网络,侵删)

Installation

First, install soaplib and a WSGI server like Flask or CherryPy. We'll use Flask here.

pip install soaplib flask

Example: Creating a Simple Calculator Service

Let's create a SOAP service with a single method, add, that takes two integers and returns their sum.

Step 1: Define the Service Logic

Create a file named calculator_service.py. We'll use Python classes and type hints to define our service interface. soaplib uses these to build the WSDL.

Python soaplib如何解析wsdl文件?-图3
(图片来源网络,侵删)
# calculator_service.py
from soaplib.core.service import rpc
from soaplib.core.model.primitive import Integer, String
from soaplib.core import Application
from soaplib.core.server import wsgi
from flask import Flask
# 1. Define the service logic in a class
class CalculatorService(object):
    """
    This is the CalculatorService class.
    The @rpc decorator marks a method as an exposed web service method.
    The type hints (Integer, Integer) define the request parameters.
    The return type hint (Integer) defines the response.
    """
    @rpc(Integer, Integer, _returns=Integer)
    def add(self, a, b):
        """
        Adds two integers.
        :param a: An integer
        :param b: An integer
        :return: The sum of a and b
        """
        print(f"Server received: add({a}, {b})")
        return a + b
# 2. Create a Flask application
flask_app = Flask(__name__)
# 3. Create the soaplib application and mount it to the Flask app
#    The first argument is the service class.
#    The second is the service name, which will appear in the WSDL.
soap_application = Application([CalculatorService], 'CalculatorSoapService')
# Mount the SOAP application to a specific URL path
wsgi_application = wsgi.Application(soap_application)
flask_app.wsgi_app = wsgi_application
if __name__ == '__main__':
    # 4. Run the Flask development server
    #    This server will serve both the WSDL and handle SOAP requests.
    #    The WSDL will be available at: http://localhost:5000/?wsdl
    print("Starting server on http://localhost:5000/?wsdl")
    flask_app.run(host='0.0.0.0', port=5000, debug=True)

Step 2: Run the Server

Execute the Python script:

python calculator_service.py

You will see output indicating the server is running. You can now access the WSDL definition for your service by navigating to http://localhost:5000/?wsdl in your web browser. You will see an XML document describing your add operation.

Step 3: Create a Client to Test the Service

Now, let's create a Python client to use this service. We can use zeep for this, as it's the modern standard for SOAP clients.

First, install zeep: pip install zeep

Create a client script (calculator_client.py):

# calculator_client.py
from zeep import Client
# The URL of the WSDL file our service is exposing
wsdl_url = "http://localhost:5000/?wsdl"
try:
    # Create a Zeep client from the WSDL
    client = Client(wsdl_url)
    # The client has a 'service' attribute. You can access the
    # methods defined in the WSDL as attributes of this service object.
    # The names are typically PascalCased.
    result = client.service.Add(a=10, b=25)
    print(f"Client received result: {result}")
except Exception as e:
    print(f"An error occurred: {e}")

Run the client script in a new terminal:

python calculator_client.py

Expected Output:

  • Server Terminal:

    Starting server on http://localhost:5000/?wsdl
    127.0.0.1 - - [ ... ] "POST / HTTP/1.1" 200 -
    Server received: add(10, 25)
  • Client Terminal:

    Client received result: 35

The Modern Alternative: spyne

spyne is a successor to soaplib and is actively maintained. It's more powerful and flexible. The concept is very similar.

Installation

pip install spyne flask

Example: The Same Calculator Service in spyne

The code looks very similar, but uses spyne's decorators and application structure.

# calculator_service_spyne.py
from spyne import Application, rpc, ServiceBase, Integer
from spyne.protocol.soap import Soap11
from spyne.server.wsgi import WsgiApplication
from flask import Flask
# 1. Define the service logic
class CalculatorService(ServiceBase):
    """
    This is the CalculatorService class using spyne.
    @rpc marks a method as an exposed web service method.
    The arguments are defined in the decorator.
    """
    @rpc(Integer, Integer, _returns=Integer)
    def add(self, a, b):
        """
        Adds two integers.
        """
        print(f"Spyne Server received: add({a}, {b})")
        return a + b
# 2. Create the spyne application
#    The service_class is your service definition.
#    The 'in_protocol' and 'out_protocol' define the SOAP version.
soap_application = Application([CalculatorService],
                              tns='CalculatorSoapService',
                              in_protocol=Soap11(validator='lxml'),
                              out_protocol=Soap11())
# 3. Create a Flask app and mount the spyne application
flask_app = Flask(__name__)
wsgi_application = WsgiApplication(soap_application)
flask_app.wsgi_app = wsgi_application
if __name__ == '__main__':
    # 4. Run the server
    #    The WSDL will be at: http://localhost:5000/?wsdl
    print("Starting Spyne server on http://localhost:5000/?wsdl")
    flask_app.run(host='0.0.0.0', port=5000, debug=True)

You can run this server and use the exact same zeep client to test it. The output will be identical.


Consuming an Existing WSDL with zeep

Often, your task is not to create a service, but to use one. Someone else has already provided a WSDL file. This is where zeep excels.

Let's use a public test WSDL: http://www.dneonline.com/calculator.asmx?wsdl

This is a calculator service similar to the one we built.

# wsdl_client.py
from zeep import Client
# The URL of a public WSDL file
wsdl_url = "http://www.dneonline.com/calculator.asmx?wsdl"
try:
    # 1. Create a Zeep client from the WSDL
    client = Client(wsdl_url)
    # 2. Inspect the service
    # You can print the client's service object to see available methods
    print("Available operations:", client.wsdl.dump())
    # 3. Call a method on the service
    # Note: The method names are often PascalCased in the WSDL.
    # Let's call the 'Add' operation.
    result = client.service.Add(10, 5)
    print(f"10 + 5 = {result}")
    # Let's try another operation: Subtract
    result_subtract = client.service.Subtract(20, 8)
    print(f"20 - 8 = {result_subtract}")
except Exception as e:
    print(f"An error occurred: {e}")

Run this script:

python wsdl_client.py

Expected Output:

Available operations: ... (a lot of information about the WSDL structure)
10 + 5 = 15
20 - 8 = 12

Summary and Recommendation

Feature soaplib (Legacy) spyne (Modern) zeep (Client)
Purpose Build SOAP servers Build SOAP servers Consume SOAP services (clients)
Status Inactive (since 2025) Active Active
WSDL Handling Generates WSDL from Python code Generates WSDL from Python code Parses existing WSDL to make calls
Recommendation Avoid for new projects. Use only for maintaining old code. Recommended for building new SOAP servers in Python. The standard for building SOAP clients in Python.

Final Advice:

  • If you need to build a new SOAP server, use spyne.
  • If you need to consume an existing SOAP service, use zeep.
  • Only use soaplib if you are forced to maintain or extend a legacy application that already uses it.
分享:
扫描分享到社交APP
上一篇
下一篇