python - 处理来自 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 语句中捕获响应输出 []?
解决方案
假设如果失败则self.method()
返回:[]
get
response = self.method()
if not response:
print 'response missing'
else:
do_things(reponse)
bool()
这个片段使用了一个隐式转换的事实,如果列表为空,则response
计算结果为。False
它基本上是一个更具可读性的版本:if response == []
推荐阅读
- vue.js - Vuetify 自动完成显示 [object Object]
- csv - 如何在 Blazemeter 中运行 groovy 脚本,尝试访问 csv 文件数据?
- php - Bootstrap 4 水平滚动
- javascript - Mapbox GL 中的 MaxBounds 和自定义不对称填充
- debugging - 汇编语言中的除法(AT&T 语法)生成浮点异常
- php - 如何在 Laravel 中将文件下载为 .xlsx
- php - 带有 InstanceProfile 的 PHP AWS AssumeRole 抛出异常
- r - R 闪亮的绘图颜色有条件地基于单独数据帧上的值
- laravel - 我搜索了我的 Laravel 5.8 站点,它向我抛出了这个错误:“不能使用 stdClass 类型的对象作为数组”
- matlab - 我们如何在 Matlab 中从 csv 导入时间序列数据?