如何移除Spyne WebService响应中的<tns:objects>标签?
<tns:objects> Tag in Spyne WebService Responses Absolutely! You can absolutely get rid of that <tns:objects> wrapper tag while keeping all other parts of your response structure intact in Spyne. Let me walk you through the exact fixes based on your current code setup:
Scenario 1: Your response uses a ComplexModel with an Array field
If your current return structure wraps the array in a ComplexModel (like a response container), you just need to modify the Array definition to disable the wrapper tag.
Original Code (with <tns:objects> tag)
from spyne import Application, rpc, ServiceBase, Integer, Unicode from spyne.model.complex import ComplexModel, Array from spyne.protocol.soap import Soap11 from spyne.server.wsgi import WsgiApplication class MyDataModel(ComplexModel): id = Integer name = Unicode # This model generates the <tns:objects> wrapper class MyApiResponse(ComplexModel): objects = Array(MyDataModel) class MyWebService(ServiceBase): @rpc(_returns=MyApiResponse) def fetch_data(self): sample_data = [ MyDataModel(id=1, name="Alice"), MyDataModel(id=2, name="Bob") ] return MyApiResponse(objects=sample_data) # Initialize app app = Application( [MyWebService], 'com.yournamespace', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11() ) wsgi_app = WsgiApplication(app)
Fixed Code (without <tns:objects> tag)
Just add the wrapper=None parameter to the Array field definition:
class MyApiResponse(ComplexModel): # Disable the wrapper tag entirely objects = Array(MyDataModel, wrapper=None)
This will make your response output the MyDataModel elements directly under the response root, with no <tns:objects> wrapping them.
Scenario 2: You're directly returning an Array from your service method
If your service method returns an Array directly (without a wrapping ComplexModel), replace Array with Iterable or add wrapper=None to the Array definition.
Fixed Code Option 1: Use Iterable
from spyne.model.complex import Iterable class MyWebService(ServiceBase): # Use Iterable instead of Array to avoid the wrapper tag @rpc(_returns=Iterable(MyDataModel)) def fetch_data(self): return [ MyDataModel(id=1, name="Alice"), MyDataModel(id=2, name="Bob") ]
Fixed Code Option 2: Keep Array with wrapper=None
class MyWebService(ServiceBase): # Add wrapper=None to the Array return type @rpc(_returns=Array(MyDataModel, wrapper=None)) def fetch_data(self): return [ MyDataModel(id=1, name="Alice"), MyDataModel(id=2, name="Bob") ]
Both options will produce a response with no <tns:objects> tag, while preserving all other elements and their structure.
内容的提问来源于stack exchange,提问作者jcgarciaca

