如何在肥皂水中使用打好字的解组器?

2024-07-05 07:30:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有处理suds.client.Client(...).service.GetFoo()输出的现有代码。现在,部分流已经改变,我们不再使用SOAP,而是通过其他渠道接收相同的XML。我想通过使用suds类型的解组器重新使用现有代码,但到目前为止还没有成功。你知道吗

我90%的时间都是使用基本的解组器:

tree = suds.umx.basic.Basic().process(xmlroot)

这给了我一个很好的带有属性的对象树,这样预先存在的代码就可以访问tree[some_index].someAttribute,但是值当然总是一个字符串,而不是一个整数或日期之类的,所以代码仍然不能按原样重用。你知道吗

原始类:

class SomeService(object):
    def __init__(self):
        self.soap_client = Client(some_wsdl_url)

    def GetStuff(self):
        return self.soap_client.service.GetStuff()

几乎有效的替代品:

class SomeSourceUntyped(object):
    def __init__(self):
        self.url = some_url

    def GetStuff(self):
        xmlfile = urllib2.urlopen(self.url)
        xmlroot = suds.sax.parser.Parser().parse(xmlfile)
        if xmlroot:
            # because the parser creates a document root above the document root
            tree = suds.umx.basic.Basic().process(xmlroot)[0] 
        else:
           tree = None
        return tree

我徒劳的努力去理解肥皂水.umx.typed.Typed():

class SomeSourceTyped(object):
    def __init__(self):
        self.url = some_url
        self.schema_file_name =
            os.path.realpath(os.path.join(os.path.dirname(__file__),'schema.xsd'))
        with open(self.schema_file_name) as f:
            self.schema_node = suds.sax.parser.Parser().parse(f)
        self.schema = suds.xsd.schema.Schema(self.schema_node, "", suds.options.Options())
        self.schema_query = suds.xsd.query.ElementQuery(('http://example.com/namespace/','Stuff'))
        self.xmltype = self.schema_query.execute(self.schema)

    def GetStuff(self):
        xmlfile = urllib2.urlopen(self.url)
        xmlroot = suds.sax.parser.Parser().parse(xmlfile)
        if xmlroot:
            unmarshaller = suds.umx.typed.Typed(self.schema)
            # I'm still running into an exception, so obviously something is missing:
            # " Exception: (document, None, ), must be qref "
            # Do I need to call the Parser differently?
            tree = unmarshaller.process(xmlroot, self.xmltype)[0]
        else:
            tree = None
        return tree

这是个晦涩难懂的问题。你知道吗

额外警告:当然,我是在一个传统的系统,使用肥皂水0.3.9。你知道吗

编辑:对代码进行进一步的改进,找到了如何创建SchemaObjects


Tags: 代码selfclienttreeparserurlschemadef