简体   繁体   English

肥皂水字典结果的setdefault()

[英]setdefault() on suds soap dict results

Given the following generic code: 给出以下通用代码:

def soapQuery():
    soapuser = "Base64String"
    soappass = "Base64String"
    soapurl = 'https://url/file.ext?wsdl'
    ntlm = WindowsHttpAuthenticated(username=soapuser, password=soappass)
    client = Client(soapurl, transport=ntlm)
    result = client.service.method(something='somethingtosearchfor')
    soapfiltered = []
    for record in result.SoapRecord:
        soapfiltered.extend((str(record.value1), str(record.value2), str(record.value3), str(record.value4)))
    return zip(*[iter(soapfiltered)]*4)

When ran I get the following error: 运行时,出现以下错误:

AttributeError: SoapRecord instance has no attribute 'value3' AttributeError:SoapRecord实例没有属性“ value3”

MOST of result.SoapRecord 's returned will contain all 4 record.value 's but some do not have this. 科技部 result.SoapRecord的返回将包含所有4 record.value的但有些没有这个。 Is there a way to set a default value to be returned like None or Null ? 有没有办法设置要返回的默认值,如NoneNull I have tried throwing record.setdefault('value3', None) in there but it does not work. 我曾尝试在其中扔record.setdefault('value3', None) ,但它不起作用。 Any and all help would be appreciated. 任何和所有帮助将不胜感激。 Thank you in advance. 先感谢您。

Well, there is no Null in Python and the dict's setdefault 's default default is None . 好吧,Python中没有Null ,而dict的setdefault的默认默认值为None Btw, dictionaries cannot be accessed through the dot operator in Python (sadly, I miss the feature from JS) so basically...I don't think record is a dictionary, but rather an object instead. 顺便说一句,字典不能通过Python中的点运算符来访问(遗憾的是,我错过了JS中的功能),所以基本上...我不认为record是字典,而是对象。 To check if an object has a property, you can do hasattr(record, 'value1') for example. 要检查对象是否具有属性,可以执行hasattr(record, 'value1')例如。

Now with that all in mind, to keep everything to a single expression, you could do something like this: 现在,请记住所有这些,要将所有内容保持为单个表达式,您可以执行以下操作:

hasattr(record, 'value1') and str(record.value1) or None

This is a boolean expression and in Python, you can evaluate boolean expressions without fully casting the values to bools. 这是一个布尔表达式,在Python中,您可以评估布尔表达式而无需将值完全转换为布尔值。 So that expression will give you either the value of str(record.value1) or simply None . 因此,该表达式将为您提供str(record.value1)的值,或仅为None

Sorry if anything in this answer is wrong, I'm not familiar with the Soap library. 抱歉,如果此答案有误,我对Soap库不熟悉。

Edit: As @plaes has noted in the comments, getattr(record, 'value1', None) is a much shorter and easier way of doing it. 编辑:正如@plaes在评论中指出的那样, getattr(record, 'value1', None)是一种更短,更容易的方法。 Thank you plaes :) 谢谢皮尔斯:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM