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

x8diyxa7  于 2023-05-08  发布在  Go
关注(0)|答案(2)|浏览(102)

我想使用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.'

有人有解决办法吗?

gpnt7bae

gpnt7bae1#

错误消息说服务需要一个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'},
    # ...
}
vd8tlhqk

vd8tlhqk2#

你的错误说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)

相关问题