杰瑞科技汇

Python suds 如何在Windows上使用?

Of course! The term "Python suds window" can refer to a few different things, but it most commonly means using the suds library to interact with a SOAP web service from a Python script, often within a terminal or command-line "window."

Python suds 如何在Windows上使用?-图1
(图片来源网络,侵删)

Let's break it down. I'll cover:

  1. What is suds? (A brief explanation)
  2. How to Use suds in a Python Script (The core functionality)
  3. Troubleshooting and Common Issues (Very important for suds)
  4. The Modern Alternative: zeep (Why you should consider it)

What is suds?

suds is a lightweight SOAP client library for Python. Its name is a play on "Simple Unstructured Data SOAP" client. It was very popular for its simplicity but has been in maintenance mode for a long time.

Key characteristics:

  • Lightweight: It has minimal dependencies.
  • Simple API: It's easy to get started with for basic WSDL-based services.
  • Legacy: It's no longer actively developed. You might run into issues with modern, complex WSDLs or security standards.

Installation:

Python suds 如何在Windows上使用?-图2
(图片来源网络,侵删)
pip install suds-jurko

Note: The original suds package is unmaintained. suds-jurko is a well-maintained fork that is the recommended version to use today.


How to Use suds in a Python Script ("The Window")

This is the most likely meaning of your query. We'll write a Python script that acts as a "window" into a SOAP service.

Let's use a public test WSDL for this example: http://www.dneonline.com/calculator.asmx?wsdl. This service has simple methods like Add, Subtract, etc.

Step-by-Step Example

Goal: Call the Add method to add two numbers (e.g., 5 and 3).

Python suds 如何在Windows上使用?-图3
(图片来源网络,侵删)
# First, install the library if you haven't:
# pip install suds-jurko
from suds.client import Client
from suds.sax.element import Element
# The URL of the WSDL file for the web service
wsdl_url = 'http://www.dneonline.com/calculator.asmx?wsdl'
try:
    # 1. Create a client object by pointing it to the WSDL
    # This single line will download and parse the WSDL, showing you the available services and methods.
    client = Client(wsdl_url)
    # 2. Inspect the service (optional, but very helpful)
    # This prints the available services, ports, and operations (methods).
    # This is your first "window" into the service.
    print("--- Service Information ---")
    print(client)
    print("\n")
    # 3. Prepare the arguments for the method call
    # The WSDL defines the structure of the input parameters.
    # For the 'Add' method, it expects two 'int' arguments.
    # suds creates Python objects that match the WSDL schema.
    # You can see the types by inspecting client.factory
    print("--- Available Types ---")
    print(client.factory)
    print("\n")
    # 4. Create the input data using the factory
    # The factory knows how to create objects for the service's data types.
    # The type name 'int' is defined in the WSDL's schema.
    arg1 = client.factory.create('int')
    arg1.value = 5
    arg2 = client.factory.create('int')
    arg2.value = 3
    # 5. Call the web service method
    # The method name ('Add') is case-sensitive and must match the WSDL.
    # Pass the arguments as keyword arguments.
    print("--- Calling Web Service ---")
    result = client.service.Add(intA=arg1, intB=arg2)
    # 6. Print the result
    # The result is a suds object. You can access its attributes.
    print(f"The result of the Add operation is: {result}")
except Exception as e:
    print(f"An error occurred: {e}")

How to Run It

  1. Save the code above as a file, e.g., soap_client.py.
  2. Open your terminal or command prompt ("window").
  3. Run the script: python soap_client.py

Expected Output

You will first see a lot of information as suds parses the WSDL. This is the "window" into the service's structure.

--- Service Information ---
Service (Calculator) tns="http://tempuri.org/"
  Port (CalculatorSoap) address="http://www.dneonline.com/calculator.asmx"
    Operations (4):
     Add, Subtract, Multiply, Divide
--- Available Types ---
(q0:int){
   value   : int
}
--- Calling Web Service ---
The result of the Add operation is: 8

Troubleshooting and Common Issues

suds can be tricky. Here are some common problems and solutions.

Issue 1: WebFault: Server did not recognize the value of HTTP Header

Cause: This is almost always a SOAP Header issue. Many web services require authentication or other information to be passed in the SOAP header, not the body.

Solution: You need to create a header object and tell the client to use it.

from suds.client import Client
from suds.sax.element import Element
wsdl_url = 'https://some.service/that/requires/headers?wsdl'
client = Client(wsdl_url)
# Create the header element
# The namespace ('ns1') and element name ('AuthHeader') depend on the WSDL
header = Element('AuthHeader').set(ns='ns1') 
# Add child elements to the header
username = Element('Username').set(ns='ns1')
username.setText('myuser')
header.append(username)
password = Element('Password').set(ns='ns1')
password.setText('mypass')
header.append(password)
# Tell the client to use this header for all future calls
client.set_options(soapheaders=header)
# Now your service call will include the header
result = client.service.SomeMethod()
print(result)

Issue 2: ValueError: No service defined

Cause: The WSDL file might be malformed, or the service name in the WSDL is not what suds expects.

Solution: Inspect the client object more carefully. The service name might be different.

client = Client(wsdl_url)
# Print the service information again, but this time access it directly
print("Service:", client.wsdl.services)
print("Ports:", client.wsdl.services)

Issue 3: TypeError: ... got an unexpected keyword argument '...'

Cause: The parameter name you are using in your Python code does not match the exact name defined in the WSDL. SOAP parameter names are case-sensitive.

Solution: Check the WSDL or inspect the client.factory to see the correct parameter names.

# If the WSDL defines the parameter as 'IntA', not 'intA'
# This will fail:
# result = client.service.Add(IntA=5, IntB=3) # Correct
# result = client.service.Add(intA=5, intB=3) # Incorrect if WSDL says IntA

The Modern Alternative: zeep

For any new project, zeep is highly recommended over suds. It's actively maintained, more robust, handles complex types and WSDLs better, and has a more modern, intuitive API.

Why zeep is better:

  • Active Development: Regularly updated.
  • Better WSDL Support: Handles imports, includes, and complex schemas more reliably.
  • Intuitive API: You often work directly with Python native types (like dicts and lists) instead of special suds objects.
  • Excellent Documentation: Much easier to get help.

zeep Example (Same Task)

pip install zeep
from zeep import Client
wsdl_url = 'http://www.dneonline.com/calculator.asmx?wsdl'
try:
    # 1. Create the client
    client = Client(wsdl_url)
    # 2. Inspect the service (zeep's way)
    # This shows you the types and services in a clean way.
    print("--- Service Information ---")
    print(client.wsdl.dump())
    print("\n")
    # 3. Call the method directly with Python-native types
    # zeep is smart enough to map Python types (int) to the required WSDL types.
    # No need for a 'factory' for simple types.
    print("--- Calling Web Service ---")
    result = client.service.Add(intA=5, intB=3)
    print(f"The result of the Add operation is: {result}")
except Exception as e:
    print(f"An error occurred: {e}")

As you can see, zeep is often cleaner and requires less boilerplate code to achieve the same result.

分享:
扫描分享到社交APP
上一篇
下一篇