Python包-aiohttp有一个警告信息“未关闭的客户端会话"; [英] Python package - aiohttp has a warning message "Unclosed client session"
本文介绍了Python包-aiohttp有一个警告信息“未关闭的客户端会话";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的代码如下:
导入异步导入 aiohttp网址 = ['http://www.163.com/','http://www.sina.com.cn/','https://www.hupu.com/','http://www.csdn.net/']异步定义 get_url_data(u):"""读取网址数据:参数你::返回:"""打印('运行',你)resp = await aiohttp.ClientSession().get(url=u)标头 = resp.headers打印(u,标题)返回标题异步定义 request_url(u):"""主函数:参数你::返回:"""res = await get_url_data(u)返回资源loop = asyncio.get_event_loop()task_lists = asyncio.wait([request_url(u) for u in urls])loop.run_until_complete(task_lists)循环关闭()
当我运行我的代码时,它显示一条警告消息:未封闭的客户会话
有人可以给我一些解决方案吗?
非常感谢
解决方案
最后你应该关闭连接.您有 2 个选择:
您可以手动关闭连接:
import aiohttpsession = aiohttp.ClientSession()# 在这里使用会话session.close()
或者您可以将它与上下文管理器一起使用:
import aiohttp导入异步异步def fetch(客户端):与 client.get('http://python.org') 异步作为响应:断言 resp.status == 200返回 await resp.text()异步定义主(循环):与 aiohttp.ClientSession(loop=loop) 作为客户端异步:html = 等待获取(客户端)打印(html)loop = asyncio.get_event_loop()loop.run_until_complete(main(loop))
<块引用>
客户端会话支持用于自关闭的上下文管理器协议.
My code is as follows:
import asyncio
import aiohttp
urls = [
'http://www.163.com/',
'http://www.sina.com.cn/',
'https://www.hupu.com/',
'http://www.csdn.net/'
]
async def get_url_data(u):
"""
read url data
:param u:
:return:
"""
print('running ', u)
resp = await aiohttp.ClientSession().get(url=u)
headers = resp.headers
print(u, headers)
return headers
async def request_url(u):
"""
main func
:param u:
:return:
"""
res = await get_url_data(u)
return res
loop = asyncio.get_event_loop()
task_lists = asyncio.wait([request_url(u) for u in urls])
loop.run_until_complete(task_lists)
loop.close()
When i running my code, it's display a warning message: Unclosed client session
Anybody can give me some solutions about that?
Thanks a lot
解决方案
You should close the connection in the end. You have 2 options:
You can close the connection manually:
import aiohttp
session = aiohttp.ClientSession()
# use the session here
session.close()
Or you can use it with a contex manager:
import aiohttp
import asyncio
async def fetch(client):
async with client.get('http://python.org') as resp:
assert resp.status == 200
return await resp.text()
async def main(loop):
async with aiohttp.ClientSession(loop=loop) as client:
html = await fetch(client)
print(html)
loop = asyncio.get_event_loop()
loop.run_until_complete(main(loop))
The client session supports the context manager protocol for self closing.
这篇关于Python包-aiohttp有一个警告信息“未关闭的客户端会话";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文