Python调用response.json()出现AttributeError错误如何解决?
报错根因
你在do_login函数中给回调函数传的参数类型不统一:
- 账号密码为空的场景:你用
json.dumps把响应字典转成了字符串类型传给callback - 正常请求场景:你把
requests.post返回的Response对象传给callback
而on_response回调里统一对入参调用.json()方法,字符串没有这个方法,自然触发AttributeError。
解决方案
以下两种方案都不需要改造do_something_with_this_error方法,符合你的需求:
方案1:从源头统一回调入参类型(最推荐)
修改do_login函数,确保两种场景传给callback的参数类型完全一致,统一先把响应内容解析为字典再传:
def do_login(username, password, callback): if(username == "" and password == ""): # 直接返回字典,不用转json字符串 response = {"resultCode":401,'status': 'error', 'error': 'Please enter a username and password'} callback(response) else: url = "xxxxxxxxxxxxxx" payload = json.dumps({"username": username, "password": password}) headers = {'Content-Type': 'application/json'} resp = requests.post(url+"/users/getuser", data=payload,headers=headers) # 正常请求也先把响应解析为字典再传 callback(resp.json()) def login_button_fuction(): def on_response(response): # 现在response已经是字典了,直接取值即可 if response["resultCode"] == 100: print("success") else: error = response["error"] do_something_with_this_error()
方案2:在回调里兼容两种参数类型(适合不能修改do_login逻辑的场景)
如果无法改动do_login的现有逻辑,就在on_response里先判断入参类型再做解析:
def login_button_fuction(): def on_response(response): # 先统一把response转成字典 if isinstance(response, str): resp_dict = json.loads(response) else: resp_dict = response.json() # 后续统一用resp_dict操作 if resp_dict["resultCode"] == 100: print("success") else: error = resp_dict["error"] do_something_with_this_error()
内容的提问来源于stack exchange,提问作者lexi
相关产品推荐
相关产品推荐

