python3 协程Unclosed client session client_session:

学习了崔大神的异步协程的使用方法,代码运行的时候出现如标题的警告很是烦人,在这里记录下解决方法。

解决方法就是在session.close()之前加await

首先看下代码:

定义一个flask服务器

from flask import Flask
import time

app = Flask(__name__)


@app.route('/')
def index():
    time.sleep(3)
    return 'Hello!'

if __name__ == '__main__':
    app.run(threaded=True)

运行后用python去异步请求:

import asyncio
import aiohttp
import time

start = time.time()


async def get(url):
    session = aiohttp.ClientSession()
    response = await session.get(url)
    result = await response.text()
    session.close()
    return result


async def request():
    url = 'http://127.0.0.1:5000'
    print('Waiting for', url)
    result = await get(url)
    print('Get response from', url, 'Result:', result)


tasks = [asyncio.ensure_future(request()) for _ in range(5)]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))

end = time.time()
print('Cost time:', end - start)

控制台输出:

python3 协程Unclosed client session client_session: <aiohttp.client.ClientSession object at 0x0918BAC0>_第1张图片

 

 一片警告,应该是版本更新,所以用法有点不同

解决:session.close()前加await

await session.close()

python3 协程Unclosed client session client_session: <aiohttp.client.ClientSession object at 0x0918BAC0>_第2张图片

 

 页面清爽很多。。。

参考:https://stackoverflow.com/questions/54807599/aiohttp-unclosed-client-session-client-session

静觅 » Python中异步协程的使用方法介绍

你可能感兴趣的:(python3 协程Unclosed client session client_session: )