簡體   English   中英

在銷毀父對象上關閉aiohttp.ClientSession

[英]Closing aiohttp.ClientSession on parent object destruction

我正在編寫一個用於訪問REST API的CLI。 我已經在異步初始化方法中定義了aiohttp.ClientSession類字段_client_session

如何正確關閉aiohttp.ClientSession 如果我做:

import asyncio
import aiohttp


class Profile:                                                                    
    def __init__(self, loop):                                                     
        self._loop = loop                                                         
        self._client_session = None                                               

    def __del__(self):                                                            
        self._loop.run_until_complete(self._client_session.close())              

    async def async_init(self):
        self._client_session = aiohttp.ClientSession()                           

    @classmethod
    async def create(cls, loop):
        self = cls(loop)
        await self.async_init()
        return self


loop = asyncio.get_event_loop()
profile = loop.run_until_complete(Profile.create(loop))                          
loop.close()

我得到這個:

Exception ignored in: <bound method Profile.__del__ of <profile.Profile object at 0x7f8ab82e15c0>>
Traceback (most recent call last):
File "/home/rominf/projects/profile/profile/__init__.py", line 197, in __del__
File "/home/rominf/.pyenv/versions/3.6.6/lib/python3.6/asyncio/base_events.py", line 444, in run_until_complete
File "/home/rominf/.pyenv/versions/3.6.6/lib/python3.6/asyncio/base_events.py", line 358, in _check_closed
RuntimeError: Event loop is closed
sys:1: RuntimeWarning: coroutine 'ClientSession.close' was never awaited
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x7f8ab43bf588>
Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x7f8ab28a06a8>, 11519.944147989)]']
connector: <aiohttp.connector.TCPConnector object at 0x7f8ab43bf3c8>

我了解發生這種情況是有原因的:我在垃圾回收器刪除profile之前關閉了loop 解決的辦法是使用del手動將其del ,但是我不想這樣做。

有沒有辦法在事件循環關閉之前注冊將來執行的方法?

asyncio不支持析構函數中的IO。 構造函數和屬性相同。

推薦的方法是添加async with Profileawait profile.close()支持。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM