首页 > 解决方案 > 处理来自 http get 调用的空响应

问题描述

我在 self.method() 中有一个 http get 调用,它在某些情况下仅在响应链接中返回 [ ]。我想使用此输出以另一种方法处理异常,例如

if type(self.method()) is 'NoneType':
   print "The object   is  not  present"
else:
    self.method2()

我收到类似的错误

AttributeError: 'Response' object has no attribute 'URL'

如何在 if 语句中捕获响应输出 []?

标签: pythonrest

解决方案


假设如果失败则self.method()返回:[]get

response = self.method()
if not response:
    print 'response missing'
else:
    do_things(reponse)

bool()这个片段使用了一个隐式转换的事实,如果列表为空,则response计算结果为。False它基本上是一个更具可读性的版本:if response == []


推荐阅读