首页 > 解决方案 > Zeep:使用类型检查进行预验证

问题描述

有没有办法通过 zeep 进行类型检查来验证有效负载?Zeep 检查缺失的元素,但即使类型不正确也会发送有效负载。

例如,我有元素:

<element name="order_date" type="dateTime" minOccurs="1" maxOccurs="1"/>

当我发送错误类型时,例如'1.0'该字段,zeep 仍然接受它。后来我zeep.exceptions.Fault回来了,因为 SOAP 服务器拒绝了我的请求,因为类型错误,因为它必须是 ISO 格式的日期

我有一种方法可以通过预先创建消息然后使用库wsdl文件中提供的模式来验证它。lxml这很好用,但我不确定我是否zeep以正确的方式使用,也许它也支持开箱即用?我已经浏览了源代码,但没有找到太多。我知道zeep使用类型检查将 SOAP 响应转换回 Python,但不确定预验证。

我目前的处理方式:

# There are some missing variables, don't want to CP everything
from lxml import etree as ET

def get_xmlschema():
    wsdl_file = ...
    wsdl_tree = ET.fromstring(wsdl_file)
    return ET.XMLSchema(wsdl_tree.find('.//schema:schema', namespaces=NAMESPACES))


def prevalidate_soap_message(client, operation, *args, **kwargs):
    # zeep checks only required elements and doesn't perform type checking
    msg = client.create_message(client.service, operation, *args, **kwargs)
    payload = msg.find('*/')
    get_xmlschema().assertValid(payload)

这就是我发送有效载荷以获取上下文的方式:

client = zeep.Client(wsdl)
operation = client.service[operation_name]
payload = ... # this is python object with structure as in wsdl schema for that operation
result = operation(payload) # it raises ValidationError if elements are missing but not for types

标签: pythonsoapwsdllxmlzeep

解决方案


推荐阅读