如何检查异步HTTP会话请求状态码?解决ClientResponse属性错误
解决aiohttp异步请求中
ClientResponse无status_code属性的错误 问题描述
我编写了一段Python异步HTTP请求代码,运行时触发如下错误:
ERROR: 'ClientResponse' object has no attribute 'status_code' Target http://localhost:8080/site.html is not stable
本地部署的站点在浏览器中可正常访问,但代码执行报错,推测问题出在await response.status_code的实现上,想知道如何正确检查异步HTTP会话请求的状态码并解决该错误。
原代码如下:
async def review(url, session, **kwargs): try: #this checks the method from the list of ARGS kinda deleted the code if method == 'GET': async with session.get(url) as response: # i did some printing in the code after the if condition but it was not executed if await response.status_code == 200: print('[bold green]`[+]` [default]Target is responsive') print(response.data) return await response except Exception as err: print(f'[red]ERROR {err} Target {url} is not stable ') url_obj['stable'] = False else: url_obj['stable'] = True status = response.status_code finally: if url_obj.get('stable') is True: return f'Target is stable' else: return f'Target is unstable status code {status}' async def main(url, **kwargs): async with ClientSession() as session: data= await review(URL, session, **kwargs) print(data) def probe(url, **kwargs): asyncio. run(main(url,**kwargs))
错误原因与修正方案
核心错误点
- 属性名混淆:aiohttp的
ClientResponse对象用status表示状态码,而status_code是requests库的属性名,这是跨库API混淆导致的错误。 - 多余的
await:status是同步属性,直接访问即可,不需要加await,原代码中await response.status_code既错误又多余。 - 其他代码问题:存在缩进错误、未定义变量(
method、url_obj、URL)、response.data属性不存在(aiohttp需用read()/text()获取响应内容)等问题。
修正后的完整代码
import asyncio from aiohttp import ClientSession async def review(url, session, **kwargs): url_obj = {'stable': False} status = None # 从kwargs获取请求方法,默认使用GET method = kwargs.get('method', 'GET') try: if method == 'GET': async with session.get(url) as response: # 直接访问status属性获取状态码,无需await status = response.status if status == 200: print('[bold green][+][default]Target is responsive') # 获取响应文本内容,如需字节用await response.read() response_content = await response.text() print(response_content) url_obj['stable'] = True return response else: url_obj['stable'] = False except Exception as err: print(f'[red]ERROR {err} Target {url} is not stable ') url_obj['stable'] = False else: url_obj['stable'] = True finally: if url_obj['stable']: return 'Target is stable' else: return f'Target is unstable status code {status}' async def main(url, **kwargs): async with ClientSession() as session: # 修正变量名,使用传入的url参数而非未定义的URL data = await review(url, session, **kwargs) print(data) def probe(url, **kwargs): # 修正asyncio.run的空格问题 asyncio.run(main(url,**kwargs)) # 示例调用 probe('http://localhost:8080/site.html')
关键修正说明
- 状态码获取:将
await response.status_code改为response.status,直接访问同步属性。 - 响应内容获取:用
await response.text()(获取字符串)或await response.read()(获取字节)替代不存在的response.data。 - 变量与缩进修复:定义缺失的
url_obj、method、status变量,修正main函数中未定义的URL为参数url,统一代码缩进。 - 异常处理优化:确保
finally块中status变量始终有值,避免未定义错误。
内容的提问来源于stack exchange,提问作者geek
相关产品推荐
相关产品推荐

