如何使用 django 发送 soap 请求中的对象列表?

问题描述 投票:0回答:2

我想使用 django 向 soap 发送包含对象列表的请求;

我试过如下:

data = [{"title": "title1", "pic": "pic1"},
        {"title": "title2", "pic": "pic2"},
         ....
       ]


wsdl = 'http://test.com/Test/TEST.asmx?wsdl'
            tac_data = {
                'user': {'UserName': 'username', 'Pass': 'password'},
                'request': f"""{data}"""
            }

            client = Client(wsdl=wsdl)
            response = client.service.AddDocLossFile(**tac_data)

但是我发现了以下错误:

'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type \'ViewModels.Dto.DocLossFile\' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.\nTo fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.\nPath \'\', line 1, position 1.'

有人有解决方案吗?

python django soap
2个回答
0
投票

错误消息说服务需要一个

JSON object
,但你提供了一个
JSON array
。 你需要创造
JSON object
.

data = [{"title": "title1", "pic": "pic1"},
        {"title": "title2", "pic": "pic2"},
        #...
       ]

# Convert list of dictionaries to a dictionary of dictionaries
data_dict = {f"item{i}": item for i, item in enumerate(data)}

wsdl = 'http://test.com/Test/TEST.asmx?wsdl'
tac_data = {
    'user': {'UserName': 'username', 'Pass': 'password'},
    'request': data_dict
}

client = Client(wsdl=wsdl)
response = client.service.AddDocLossFile(**tac_data)

data_dict
将返回给你这个对象:

{
    'item0': {'title': 'title1', 'pic': 'pic1'},
    'item1': {'title': 'title2', 'pic': 'pic2'},
    # ...
}

0
投票

您的错误表明 SOAP 服务需要一个 JSON 对象,但接收的却是一个 JSON 数组。

data = {
    'title': 'example_title',
    'pic': 'example_pic'
}

# Build the SOAP request payload
tac_data = {
    'user': {'UserName': 'username', 'Pass': 'password'},
    'request': data
}

# Send the SOAP request
client = Client(wsdl=wsdl)
response = client.service.AddDocLossFile(**tac_data)

您可以使用 suds 库创建 SOAP 客户端并发送带有序列化数据的 SOAP 请求,并使用 django.core.serializers 模块将对象列表序列化为 XML 格式。

serialized_data = serialize('xml', data)

# Create a SOAP client and send the request
client = Client('http://test.com/Test/TEST.asmx?wsdl')
response = client.service.my_method(serialized_data)
© www.soinside.com 2019 - 2024. All rights reserved.