AttributeError: 'bytes'对象无'get'属性问题排查求助
问题分析:AttributeError 'bytes' object has no attribute 'get'
问题场景
调用API时触发AttributeError 'bytes' object has no attribute 'get',错误出现在代码行'name': alert.get('hostname')。
原代码
import requests from requests.auth import HTTPBasicAuth incidents = [] limit = 100 offset = 0 got_all_events = False while not got_all_events: alerts = requests.get(f'***', auth=HTTPBasicAuth('***', '***')) print(alerts) for alert in alerts: incident = { 'name': alert.get('hostname'), 'rawJSON': json.dumps(alert), } incidents.append(incident) if len(alerts) == limit: offset += limit else: got_all_events = True print(incident)
API返回结构
{ "totalSize": 0, "data": [ { "hostname": "string", "domain": "string", "tags": "string", "os": {} } ], "size": 0 }
错误原因
- 未解析API响应:
requests.get()返回的是Response对象,直接遍历这个对象会逐字节迭代,导致alert是bytes类型,自然没有get()方法。 - 未提取正确数据字段:API返回的实际数据嵌套在
data数组里,原代码没有针对这个结构做处理。 - 缺失模块导入:代码中使用了
json.dumps()但没导入json模块。 - 参数未传递:定义了
offset变量但没在请求URL中使用,无法实现分页拉取数据。 - 变量名错误:最后打印的
incident是循环内的局部变量,应该打印incidents列表。
修复方案
- 用
response.json()解析API返回的JSON数据,得到字典结构。 - 从解析后的字典中取出
data字段的数组进行遍历。 - 补充导入
json模块。 - 在请求URL中加入
offset和limit参数,实现分页逻辑。 - 修正最后打印的变量为
incidents。
修正后的完整代码
import requests import json from requests.auth import HTTPBasicAuth incidents = [] limit = 100 offset = 0 got_all_events = False while not got_all_events: # 在URL中加入分页参数,替换***为实际API地址 alerts_response = requests.get( f'***?limit={limit}&offset={offset}', auth=HTTPBasicAuth('***', '***') ) # 解析JSON响应 alerts_data = alerts_response.json() # 遍历data数组中的告警数据 for alert in alerts_data['data']: incident = { 'name': alert.get('hostname'), 'rawJSON': json.dumps(alert), } incidents.append(incident) # 根据返回的size判断是否还有更多数据 if alerts_data['size'] == limit: offset += limit else: got_all_events = True print(incidents)
内容的提问来源于stack exchange,提问作者Greg
相关产品推荐
相关产品推荐

