请教一下,为什么会输出`Unclosed connection`警告?

2022-12-17 18:12:18 +08:00
 lizhien

请教一下,为什么会输出Unclosed connection警告?
我在__aexit__明明已经close
看官方的 issue 说是什么要aiohttp==4.0才能解决? 不知道我写的代码有没有问题
现在我的解决方式屏蔽了这个warning
麻烦各位了🥺

版本

输出

代码

# -*- coding: utf-8 -*-
import asyncio

from aiohttp import ClientResponse, ClientTimeout

from common import config

from aiohttp_retry import RetryClient, ClientSession


class Request:

    def __init__(self, *args, **kwargs):
        self.client_session = ClientSession()
        self.retry_client = RetryClient(client_session=self.client_session)
        self.request = self.retry_client.request(*args, **kwargs)

    async def __aenter__(self) -> ClientResponse:
        return await self.request

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        await self.client_session.close()
        await self.retry_client.close()


def get(url, params=None, headers=None):
    if headers is None:
        headers = {}
    if params is None:
        params = {}
    return request("GET", url, params=params, headers={
        **config.http['headers'], **headers
    })


def request(method, url, params=None, headers=None, data=None):
    if headers is None:
        headers = {}
    if params is None:
        params = {}
    if data is None:
        data = {}

    return Request(
        method, config.http['http_proxy'] + url,
        params=params, proxy=config.http['proxy'],
        headers={**config.http['headers'], **headers},
        data=data, ssl=False,
        timeout=ClientTimeout(total=config.http['timeout']))


def post(url, data=None, headers=None):
    if headers is None:
        headers = {}
    if data is None:
        data = {}
    return request("POST", url, data=data, headers={
        **config.http['headers'], **headers
    })


if __name__ == '__main__':
    async def test():
        for i in range(100):
            async with request("GET", "https://www.baidu.com") as r:
                print(r.status)
    asyncio.get_event_loop().run_until_complete(test())

1911 次点击
所在节点    Python
2 条回复
ec0
2022-12-18 16:21:12 +08:00
你的代码在我这里没有报 Unclosed connection

版本
Python 3.10.8
aiohttp==3.8.3

输出
全是 200
lizhien
2022-12-18 21:35:42 +08:00
@ec0 Python3.10 就没有问题,Python3.9 有,也不知道为什么

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/903171

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX