gpt4 book ai didi

Python包-aiohttp有警告信息 "Unclosed client session"

转载 作者:太空狗 更新时间:2023-10-30 02:01:49 25 4
gpt4 key购买 nike

我的代码如下:

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()

当我运行我的代码时,它会显示一条警告消息:未关闭的客户 session

谁能给我一些解决方案?

非常感谢

最佳答案

最后你应该关闭连接。您有 2 个选择:

您可以手动关闭连接:

import aiohttp
session = aiohttp.ClientSession()
# use the session here
session.close()

或者您可以将它与上下文管理器一起使用:

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有警告信息 "Unclosed client session",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46112848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com